\input texinfo @c -*-texinfo-*-
@c %**start of header
@setfilename r4rs.info
@settitle Revised(4) Scheme
@setchapternewpage on
@c Choices for setchapternewpage are {on,off,odd}.
@paragraphindent 2
@c %**end of header
@c syncodeindex fn cp

@iftex
@finalout
@c DL: lose the egregious vertical whitespace, esp. around examples
@c but paras in @defun-like things don't have parindent
@parskip 4pt plus 1pt
@end iftex

@c  First page

@ignore
todo
"another" report?
@end ignore

@titlepage
@majorheading Revised(4) Report on the Algorithmic Language
@title Scheme
@ifset html
@subtitle Revised(4) Report on the Algorithmic Language Scheme
@end ifset
@author @sc{William Clinger and Jonathan Rees (}@i{Editors}@sc{)}
@author @sc{H. Abelson}
@author @sc{N. I. Adams IV}
@author @sc{D. H. Bartley}
@author @sc{G. Brooks}
@author @sc{R. K. Dybvig}
@author @sc{D. P. Friedman}
@author @sc{R. Halstead}
@author @sc{C. Hanson}
@author @sc{C. T. Haynes}
@author @sc{E. Kohlbecker}
@author @sc{D. Oxley}
@author @sc{K. M. Pitman}
@author @sc{G. J. Rozas}
@author @sc{G. L. Steele Jr.}
@author @sc{G. J. Sussman}
@author @sc{M. Wand}
@sp 2
@center @i{Dedicated to the Memory of ALGOL 60}
@sp 2
@ifset html
@author Converted to @TeX{}info by @sc{A. Jaffer} (jaffer@@ai.mit.edu)
@end ifset
@ifclear html
@author Converted to @TeX{}info by A. Jaffer @i{(jaffer@@ai.mit.edu)}
@page

We intend this report to belong to the entire Scheme community, and so
we grant permission to copy it in whole or in part without fee.  In
particular, we encourage implementors of Scheme to use this report as
a starting point for manuals and other documentation, modifying it as
necessary.

@sp 2
@noindent
@b{2 November 1991}

@majorheading Summary

The report gives a defining description of the programming language
Scheme.  Scheme is a statically scoped and properly tail-recursive
dialect of the Lisp programming language invented by Guy Lewis
Steele Jr.@: and Gerald Jay Sussman.  It was designed to have an
exceptionally clear and simple semantics and few different ways to
form expressions.  A wide variety of programming paradigms, including
imperative, functional, and message passing styles, find convenient
expression in Scheme.

@c vest
The introduction offers a brief history of the language and of
the report.

@c vest
The first three chapters present the fundamental ideas of the
language and describe the notational conventions used for describing the
language and for writing programs in the language.

@c vest
@ref{Expressions} and @ref{Program structure} describe
the syntax and semantics of expressions, programs, and definitions.

@c vest
@ref{Standard procedures} describes Scheme's built-in
procedures, which include all of the language's data manipulation and
input/output primitives.

@c vest
@ref{Formal syntax and semantics} provides a formal syntax for Scheme
written in extended BNF, along with a formal denotational semantics.
An example of the use of the language follows the formal syntax and
semantics.

@c vest
The appendix describes a macro facility that may be used to
extend the syntax of Scheme.

@c vest
The report concludes with a bibliography and an alphabetic index.

@ignore
todo
expand the summary so that it fills up the column.
@end ignore

@end ifclear
@end titlepage

@node Top, Introduction, (dir), (dir)

@ifinfo
@center Revised(4) Report on the Algorithmic Language Scheme

@center William Clinger and Jonathan Rees (@i{Editors})
@example
H. Abelson      R. K. Dybvig    C. T. Haynes    G. J. Rozas
N. I. Adams IV  D. P. Friedman  E. Kohlbecker   G. L. Steele Jr.
D. H. Bartley   R. Halstead     D. Oxley        G. J. Sussman
G. Brooks       C. Hanson       K. M. Pitman    M. Wand
@end example
@center @i{Dedicated to the Memory of ALGOL 60}

@display
Converted to @TeX{}info by A. Jaffer (jaffer@@ai.mit.edu)
@end display

We intend this report to belong to the entire Scheme community, and so
we grant permission to copy it in whole or in part without fee.  In
particular, we encourage implementors of Scheme to use this report as
a starting point for manuals and other documentation, modifying it as
necessary.

@sp 2
@noindent
@b{2 November 1991}
@c @center @b{*** DRAFT*** August 31, 1989}

@ifset html
@unnumbered Summary
@end ifset
@ifclear html
@majorheading Summary
@end ifclear

The report gives a defining description of the programming language
Scheme.  Scheme is a statically scoped and properly tail-recursive
dialect of the Lisp programming language invented by
@w{Guy Lewis Steele Jr.}@: and @w{Gerald Jay Sussman}.  It was designed
to have an
exceptionally clear and simple semantics and few different ways to
form expressions.  A wide variety of programming paradigms, including
imperative, functional, and message passing styles, find convenient
expression in Scheme.

@c vest
The introduction offers a brief history of the language and of
the report.

@c vest
The first three chapters present the fundamental ideas of the
language and describe the notational conventions used for describing the
language and for writing programs in the language.

@c vest
@ref{Expressions} and @ref{Program structure} describe
the syntax and semantics of expressions, programs, and definitions.

@c vest
@ref{Standard procedures} describes Scheme's built-in
procedures, which include all of the language's data manipulation and
input/output primitives.

@c vest
@ref{Formal syntax and semantics} provides a formal syntax for Scheme
written in extended BNF, along with a formal denotational semantics.
An example of the use of the language follows the formal syntax and
semantics.

@c vest
The appendix describes a macro facility that may be used to
extend the syntax of Scheme.

@c vest
The report concludes with a bibliography and an alphabetic index.

@ignore
todo
expand the summary so that it fills up the column.
@end ignore
@end ifinfo

@menu
* Introduction::
* Overview of Scheme::
* Lexical conventions::
* Basic concepts::
* Expressions::
* Program structure::
* Standard procedures::
* Formal syntax and semantics::
* Notes::
* Example::
* Macros::                      Appendix
* Bibliography and references::
* Index::                       Alphabetic index of definitions of
                                concepts, keywords, and procedures
@end menu

@page
@setchapternewpage off
@node Introduction, Overview of Scheme, Top, Top
@ifclear html
@majorheading Description of the Language
@end ifclear
@unnumbered Introduction
@setchapternewpage on
@menu
* History::
* Background::
* Acknowledgements::
@end menu

@node History, Background, Introduction, Introduction
@unnumberedsec History

Programming languages should be designed not by piling feature on top of
feature, but by removing the weaknesses and restrictions that make additional
features appear necessary.  Scheme demonstrates that a very small number
of rules for forming expressions, with no restrictions on how they are
composed, suffice to form a practical and efficient programming language
that is flexible enough to support most of the major programming
paradigms in use today.

@c Scheme has influenced the evolution of Lisp.
Scheme
was one of the first programming languages to incorporate first class
procedures as in the lambda calculus, thereby proving the usefulness of
static scope rules and block structure in a dynamically typed language.
Scheme was the first major dialect of Lisp to distinguish procedures
from lambda expressions and symbols, to use a single lexical
environment for all variables, and to evaluate the operator position
of a procedure call in the same way as an operand position.  By relying
entirely on procedure calls to express iteration, Scheme emphasized the
fact that tail-recursive procedure calls are essentially goto's that
pass arguments.  Scheme was the first widely used programming language to
embrace first class escape procedures, from which all previously known
sequential control structures can be synthesized.  More recently, building
upon the design of generic arithmetic in Common Lisp, Scheme introduced
the concept of exact and inexact numbers.
With the appendix to this report Scheme becomes the first programming
language to support hygienic macros, which permit the syntax of a
block-structured language to be extended reliably.
@c  A few
@c of these innovations have recently been incorporated into Common Lisp, while
@c others remain to be adopted.

@ignore
todo
Ramsdell:
I would like to make a few comments on presentation.  The most
important comment is about section organization.  Newspaper writers
spend most of their time writing the first three paragraphs of any
article.  This part of the article is often the only part read by
readers, and is important in enticing readers to continue.  In the
same way, The first page is most likely to be the only page read by
many SIGPLAN readers.  If I had my choice of what I would ask them to
read, it would be the material in section 1.1, the Semantics section
that notes that scheme is lexically scoped, tail recursive, weakly
typed, ... etc.  I would expand on the discussion on continutations,
as they represent one important difference between Scheme and other
languages.  The introduction, with its history of scheme, its history
of scheme reports and meetings, and acknowledgements giving names of
people that the reader will not likely know, is not that one page I
would like all to read.  I suggest moving the history to the back of
the report, and use the first couple of pages to convince the reader
that the language documented in this report is worth studying.

@end ignore

@node Background, Acknowledgements, History, Introduction
@unnumberedsec Background

@c vest
The first description of Scheme was written in
1975 @sc{[Scheme75]}.  A revised report @sc{[Scheme78]}
@ignore
todo
italicize or not?
@end ignore
appeared in 1978, which described the evolution
of the language as its MIT implementation was upgraded to support an
innovative compiler @sc{[Rabbit]}.  Three distinct projects began in
1981 and 1982 to use variants of Scheme for courses at MIT, Yale, and
Indiana University @sc{[Rees82]} @sc{[MITScheme]} @sc{[Scheme311]}.  An
introductory computer science textbook using Scheme was published in
1984 @sc{[SICP]}.

@c vest
@c As might be expected of a language used primarily for education and
@c research, Scheme has always evolved rapidly.  This was no problem when
@c Scheme was used only within MIT, but
@c vest
As Scheme became more widespread,
local dialects began to diverge until students and researchers
occasionally found it difficult to understand code written at other
sites.
Fifteen representatives of the major implementations of Scheme therefore
met in October 1984 to work toward a better and more widely accepted
standard for Scheme.
@c Participating in this workshop were Hal Abelson, Norman Adams, David
@c Bartley, Gary Brooks, William Clinger, Daniel Friedman, Robert Halstead,
@c Chris Hanson, Christopher Haynes, Eugene Kohlbecker, Don Oxley, Jonathan Rees,
@c Guillermo Rozas, Gerald Jay Sussman, and Mitchell Wand.  Kent Pitman
@c made valuable contributions to the agenda for the workshop but was
@c unable to attend the sessions.

@c Subsequent electronic mail discussions and committee work completed the
@c definition of the language.
@c Gerry Sussman drafted the section on numbers, Chris Hanson drafted the
@c sections on characters and strings, and Gary Brooks and William Clinger
@c drafted the sections on input and output.
@c William Clinger recorded the decisions of the workshop and
@c compiled the pieces into a coherent document.
@c The ``Revised revised report on Scheme'' @sc{[RRRS]}
Their report @sc{[RRRS]}
was published at MIT and Indiana University in the summer of 1985.
Another round of revision took place in the spring of 1986 @sc{[R3RS]}.
@c , again accomplished
@c almost entirely by electronic mail, resulted in the present report.
The present report reflects further revisions agreed upon in a meeting
that preceded the 1988 ACM Conference on Lisp and Functional Programming
and in subsequent electronic mail.

@c vest
@c The number 3 in the title is part of the title, not a reference to
@c a footnote.  The word ``revised'' is raised to the third power because
@c the report is a revision of a report that was already twice revised.

@ignore
todo
Write an editors' note?
@end ignore

@sp 4
@c medskip

We intend this report to belong to the entire Scheme community, and so
we grant permission to copy it in whole or in part without fee.  In
particular, we encourage implementors of Scheme to use this report as
a starting point for manuals and other documentation, modifying it as
necessary.

@node Acknowledgements,  , Background, Introduction
@unnumberedsec Acknowledgements

We would like to thank the following people for their help: Alan Bawden, Michael
Blair, George Carrette, Andy Cromarty, Pavel Curtis, Jeff Dalton, Olivier Danvy,
Ken Dickey, Andy Freeman, Richard Gabriel, Yekta G\"ursel, Ken Haase, Robert
Hieb, Paul Hudak,
Richard Kelsey, Morry Katz, Chris Lindblad, Mark Meyer, Jim Miller, Jim Philbin,
John Ramsdell, Mike Shaff, Jonathan Shapiro, Julie Sussman,
Perry Wagle, Daniel Weise, Henry Wu, and Ozan Yigit.
We thank Carol Fessenden, Daniel
Friedman, and Christopher Haynes for permission to use text from the Scheme 311
version 4 reference manual.  We thank Texas Instruments, Inc. for permission to
use text from the @emph{TI Scheme Language Reference Manual.} We gladly
acknowledge the influence of manuals for MIT Scheme, T, Scheme 84,
Common Lisp, and Algol 60.

@c vest
We also thank Betty Dexter for the extreme effort she put into
setting this report in @TeX{}, and Donald Knuth for designing the program
that caused her troubles.

@c vest
The Artificial Intelligence Laboratory of the
Massachusetts Institute of Technology, the Computer Science
Department of Indiana University, and the Computer and Information
Sciences Department of the University of Oregon supported the
preparation of this report.  Support for the MIT work was provided in part by
the Advanced Research Projects Agency of the Department of Defense under Office
of Naval Research contract N00014-80-C-0505.  Support for the Indiana
University work was provided by NSF grants NCS 83-04567 and NCS
83-03325.

@ignore
todo
Steele:

[c] There should be a very clear message to the reader that Scheme certainly
does owe debts to other sources, and one of them is Common Lisp.  While
Scheme certainly has been the pioneer in the treatment of closures and
functional programming in a Lisp framework, I think it is fair to say that
Common lisp pioneered a rational (forgive the pun) treatment of numeric data
types in a Lisp framework, and my impression is that Scheme learned
something in this area from the Common Lisp experience.

@end ignore

@c  I think the above \todo has been done. -- Will, 1991.

@c @sp 2
@c @node Description of the language, Overview of Scheme, Introduction, Top
@c @chapter Description of the language
@c  1. Structure of the language

@node Overview of Scheme, Lexical conventions, Introduction, Top
@chapter Overview of Scheme

@menu
* Semantics::
* Syntax::
* Notation and terminology::
@end menu

@node     Semantics, Syntax, Overview of Scheme, Overview of Scheme
@section Semantics

This section gives an overview of Scheme's semantics.  A
detailed informal semantics is the subject of
@ref{Basic concepts} through @ref{Standard procedures}.  For reference
purposes, @ref{Formal semantics} provides a formal
semantics of Scheme.

@c vest
Following Algol, Scheme is a statically scoped programming
language.  Each use of a variable is associated with a lexically
apparent binding of that variable.

@c vest
Scheme has latent as opposed to manifest types.  Types
are associated with values (also called objects)
@cindex @w{object}
rather than
with variables.  (Some authors refer to languages with latent types as
weakly typed or dynamically typed languages.)  Other languages with
latent types are APL, Snobol, and other dialects of Lisp.  Languages
with manifest types (sometimes referred to as strongly typed or
statically typed languages) include Algol 60, Pascal, and C.

@c vest
All objects created in the course of a Scheme computation, including
procedures and continuations, have unlimited extent.
No Scheme object is ever destroyed.  The reason that
implementations of Scheme do not (usually!)@: run out of storage is that
they are permitted to reclaim the storage occupied by an object if
they can prove that the object cannot possibly matter to any future
computation.  Other languages in which most objects have unlimited
extent include APL and other Lisp dialects.

@c vest
Implementations of Scheme are required to be properly tail-recursive.
This allows the execution of an iterative computation in constant space,
even if the iterative computation is described by a syntactically
recursive procedure.  Thus with a tail-recursive implementation,
iteration can be expressed using the ordinary procedure-call
mechanics, so that special iteration constructs are useful only as
syntactic sugar.

@c vest
Scheme procedures are objects in their own right.  Procedures can be
created dynamically, stored in data structures, returned as results of
procedures, and so on.  Other languages with these properties include
Common Lisp and ML.
@ignore
todo
Rozas: Scheme had them first.
@end ignore

@c vest
One distinguishing feature of Scheme is that continuations, which
in most other languages only operate behind the scenes, also have
``first-class'' status.  Continuations are useful for implementing a
wide variety of advanced control constructs, including non-local exits,
backtracking, and coroutines.  See @ref{Control features}.

@c vest
Arguments to Scheme procedures are always passed by value, which
means that the actual argument expressions are evaluated before the
procedure gains control, whether the procedure needs the result of the
evaluation or not.  ML, C, and APL are three other languages that always
pass arguments by value.
This is distinct from the lazy-evaluation semantics of Haskell,
or the call-by-name semantics of Algol 60, where an argument
expression is not evaluated unless its value is needed by the
procedure.

@ignore
todo
Lisp's call by value should be explained more
accurately.  What's funny is that all values are references.
@end ignore

@c vest
Scheme's model of arithmetic is designed to remain as independent as
possible of the particular ways in which numbers are represented within a
computer. In Scheme, every integer is a rational number, every rational is a
real, and every real is a complex number.  Thus the distinction between integer
and real arithmetic, so important to many programming languages, does not
appear in Scheme.  In its place is a distinction between exact arithmetic,
which corresponds to the mathematical ideal, and inexact arithmetic on
approximations.  As in Common Lisp, exact arithmetic is not limited to
integers.

@node Syntax, Notation and terminology, Semantics, Overview of Scheme
@section Syntax

Scheme, like most dialects of Lisp, employs a fully parenthesized prefix
notation for programs and (other) data; the grammar of Scheme generates a
sublanguage of the language used for data.  An important
consequence of this simple, uniform representation is the susceptibility of
Scheme programs and data to uniform treatment by other Scheme programs.

The @dfn{read}
@findex read
procedure performs syntactic as well as lexical decomposition of the
data it reads.  The @dfn{read} procedure parses its input as data
(@ref{External representations}), not as program.

The formal syntax of Scheme is described in @ref{Formal syntax}.

@node Notation and terminology,  , Syntax, Overview of Scheme
@section Notation and terminology

@menu
* Essential and non-essential features::
* Error situations and unspecified behavior::
* Entry format::
* Evaluation examples::
* Naming conventions::
@end menu

@node Essential and non-essential features, Error situations and unspecified behavior, Notation and terminology, Notation and terminology
@subsection Essential and non-essential features

It is required that every implementation of Scheme support
features that are marked as being @dfn{essential}.  Features not
explicitly marked as essential are not essential.  Implementations are
free to omit non-essential features of Scheme or to add extensions,
provided the extensions are not in conflict with the language reported
here.  In particular, implementations must support portable code by
providing a syntactic mode that preempts no lexical conventions of this
report and reserves no identifiers other than those listed as syntactic
keywords in @ref{Identifiers}.

@node Error situations and unspecified behavior, Entry format, Essential and non-essential features, Notation and terminology
@subsection Error situations and unspecified behavior

@cindex @w{error}
When speaking of an error situation, this report uses the phrase ``an
error is signalled'' to indicate that implementations must detect and
report the error.  If such wording does not appear in the discussion of
an error, then implementations are not required to detect or report the
error, though they are encouraged to do so.  An error situation that
implementations are not required to detect is usually referred to simply
as ``an error.''

@c vest
For example, it is an error for a procedure to be passed an argument that
the procedure is not explicitly specified to handle, even though such
domain errors are seldom mentioned in this report.  Implementations may
extend a procedure's domain of definition to include such arguments.

@c vest
This report uses the phrase ``may report a violation of an
implementation restriction'' to indicate circumstances under which an
implementation is permitted to report that it is unable to continue
execution of a correct program because of some restriction imposed by the
implementation.  Implementation restrictions are of course discouraged,
but implementations are encouraged to report violations of implementation
restrictions.
@cindex @w{implementation restriction}

@c vest
For example, an implementation may report a violation of an
implementation restriction if it does not have enough storage to run a
program.

@c vest
If the value of an expression is said to be ``unspecified,'' then
the expression must evaluate to some object without signalling an error,
but the value depends on the implementation; this report explicitly does
not say what value should be returned.
@cindex @w{unspecified}

@ignore
todo
Talk about unspecified behavior vs. unspecified values.
@end ignore

@ignore
todo
Look at KMP's situations paper.
@end ignore

@node Entry format, Evaluation examples, Error situations and unspecified behavior, Notation and terminology
@subsection Entry format

@ref{Expressions} and @ref{Standard procedures} are organized
into entries.  Each entry describes one language feature or a group of
related features, where a feature is either a syntactic construct or a
built-in procedure.  An entry begins with one or more header lines of the form

@deffn {essential @var{category}} template
if the feature is an essential feature, or simply

@deffnx {@var{category}} template

@noindent
if the feature is not an essential feature.
@end deffn

If @var{category} is ``syntax'', the entry describes an expression
type, and the header line gives the syntax of the expression type.
Components of expressions are designated by syntactic variables, which
are written using angle brackets, for example, @r{<expression>},
@r{<variable>}.  Syntactic variables should be understood to denote segments of
program text; for example, @r{<expression>} stands for any string of
characters which is a syntactically valid expression.  The notation
@example
@r{<thing 1>} @dots{}
@end example

@noindent
indicates zero or more occurrences of a @r{<thing>}, and
@example
@r{<thing 1>} @r{<thing 2>} @dots{}
@end example

@noindent
indicates one or more occurrences of a @r{<thing>}.

If @var{category} is ``procedure'', then the entry describes a procedure, and
the header line gives a template for a call to the procedure.  Argument
names in the template are @var{italicized}.  Thus the header line

@deffn {essential procedure} vector-ref vector k

@noindent
indicates that the essential built-in procedure @code{vector-ref} takes
two arguments, a vector @var{vector} and an exact non-negative integer
@var{k} (see below).  The header lines

@deffnx {essential procedure} make-vector k
@deffnx {procedure} make-vector k fill

@noindent
indicate that in all implementations, the @code{make-vector} procedure
must be defined to take one argument, and some implementations will
extend it to take two arguments.
@end deffn

@c label typeconventions --> Entry format
It is an error for an operation to be presented with an argument that it
is not specified to handle.  For succinctness, we follow the convention
that if an argument name is also the name of a type listed in
@ref{Disjointness of types}, then that argument must be of the named type.
For example, the header line for @code{vector-ref} given above dictates that the
first argument to @code{vector-ref} must be a vector.  The following naming
conventions also imply type restrictions:
@itemize @bullet
@item @var{obj} any object
@item @var{list}, @var{list1}, @dots{}@var{listj}, @dots{}	list (see @ref{Pairs and lists})
@item @var{z}, @var{z1}, @dots{}@var{zj}, @dots{}	complex number
@item @var{x}, @var{x1}, @dots{}@var{xj}, @dots{}	real number
@item @var{y}, @var{y1}, @dots{}@var{yj}, @dots{}	real number
@item @var{q}, @var{q1}, @dots{}@var{qj}, @dots{}	rational number
@item @var{n}, @var{n1}, @dots{}@var{nj}, @dots{}	integer
@item @var{k}, @var{k1}, @dots{}@var{kj}, @dots{}	exact non-negative integer
@end itemize

@ignore
todo
Provide an example entry??
@end ignore

@node Evaluation examples, Naming conventions, Entry format, Notation and terminology
@subsection Evaluation examples

The symbol ``@result{}'' used in program examples should be read
``evaluates to.''  For example,

@lisp
(* 5 8)                     @result{}  40
@end lisp

@noindent
means that the expression @code{(* 5 8)} evaluates to the object @code{40}.
Or, more precisely:  the expression given by the sequence of characters
``@code{(* 5 8)}'' evaluates, in the initial environment, to an object
that may be represented externally by the sequence of characters
``@code{40}''.  See @ref{External representations} for a
discussion of external
representations of objects.

@node Naming conventions,  , Evaluation examples, Notation and terminology
@subsection Naming conventions

By convention, the names of procedures that always return a boolean
value usually end
in ``@samp{?}''.  Such procedures are called predicates.
@vindex ?

By convention, the names of procedures that store values into previously
allocated locations (see @ref{Storage model}) usually end in
``@samp{!}''.
Such procedures are called mutation procedures.
By convention, the value returned by a mutation procedure is unspecified.
@vindex !

By convention, ``@samp{->}'' appears within the names of procedures that
take an object of one type and return an analogous object of another type.
For example, @code{list->vector} takes a list and returns a vector whose
@findex list->vector
elements are the same as those of the list.
@vindex ->

@ignore
todo
Terms that need defining: thunk, command (what else?).
@end ignore

@c  Lexical structure

@c @page
@node Lexical conventions, Basic concepts, Overview of Scheme, Top
@chapter Lexical conventions

This section gives an informal account of some of the lexical
conventions used in writing Scheme programs.  For a formal syntax of
Scheme, see @ref{Formal syntax}.

@c vest
Upper and lower case forms of a letter are never distinguished
except within character and string constants.  For example, @code{Foo}
is
@findex foo
the same identifier as @code{FOO}, and @code{#x1AB} is the same number
as
@findex FOO
@code{#X1ab}.

@menu
* Identifiers::
* Whitespace and comments::
* Other notations::
@end menu

@node Identifiers, Whitespace and comments, Lexical conventions, Lexical conventions
@section Identifiers

Most identifiers
@cindex @w{identifier}
allowed by other programming
languages are also acceptable to Scheme.  The precise rules for forming
identifiers vary among implementations of Scheme, but in all
implementations a sequence of letters, digits, and ``extended alphabetic
characters'' that begins with a character that cannot begin a number is
an identifier.  In addition, @code{+}, @code{-}, and @code{...} are identifiers.
@findex +
@findex -
@findex ...
Here are some examples of identifiers:

@lisp
lambda                   q
list->vector             soup
+                        V17a
<=?                      a34kTMNs
the-word-recursion-has-many-meanings
@end lisp

Extended alphabetic characters may be used within identifiers as if
they were letters.  The following are extended alphabetic characters:

@lisp
+ - . * / < = > ! ? : $ % _ & ~ ^
@end lisp

See @ref{Lexical structure} for a formal syntax of identifiers.

@c vest
Identifiers have several uses within Scheme programs:
@itemize @bullet
@item Certain identifiers are reserved for use as syntactic keywords
(see below).
@cindex syntactic keyword
@cindex keyword
@c   (This does not preclude their use as identifiers
@c as well, although in certain situations ambiguities can result if this is done.)

@item Any identifier that is not a syntactic keyword may be used as a
variable (see @ref{Variables and regions}).
@cindex variable

@item When an identifier appears as a literal or within a literal
(see @ref{Literal expressions}), it is being used to denote a
@emph{symbol} (see @ref{Symbols}).

@end itemize

@c label keywordsection --> Identifiers
The following identifiers are syntactic keywords, and should not be used
as variables:

@lisp
=>           do            or
and          else          quasiquote
begin        if            quote
case         lambda        set!
cond         let           unquote
define       let*          unquote-splicing
delay        letrec
@end lisp

Some implementations allow all identifiers, including syntactic
keywords, to be used as variables.  This is a compatible extension to
the language, but ambiguities in the language result when the
restriction is relaxed, and the ways in which these ambiguities are
resolved vary between implementations.

@node Whitespace and comments, Other notations, Identifiers, Lexical conventions
@section Whitespace and comments

@dfn{Whitespace} characters are spaces and newlines.
(Implementations typically provide additional whitespace characters such
as tab or page break.)  Whitespace is used for improved readability and
as necessary to separate tokens from each other, a token being an
indivisible lexical unit such as an identifier or number, but is
otherwise insignificant.  Whitespace may occur between any two tokens,
but not within a token.  Whitespace may also occur inside a string,
where it is significant.

A semicolon (@code{;}) indicates the start of a comment.
@cindex @w{comment}
@vindex @w{;}
The comment continues to the end of the line on which the semicolon
appears.  Comments are invisible to Scheme, but the end of the line is
visible as whitespace.  This prevents a comment from appearing in the
middle of an identifier or number.

@lisp
;;; The FACT procedure computes the factorial
;;; of a non-negative integer.
(define fact
  (lambda (n)
    (if (= n 0)
        1        ;Base case: return 1
        (* n (fact (- n 1))))))
@end lisp

@node Other notations,  , Whitespace and comments, Lexical conventions
@section Other notations

@ignore
todo
Rewrite?
@end ignore

For a description of the notations used for numbers, see
@ref{Numbers}.

@table @t
@item . + -
These are used in numbers, and may also occur anywhere in an identifier
except as the first character.  A delimited plus or minus sign by itself
is also an identifier.
A delimited period (not occurring within a number or identifier) is used
in the notation for pairs (@ref{Pairs and lists}), and to indicate a
rest-parameter in a  formal parameter list (@ref{Lambda expressions}).
A delimited sequence of three successive periods is also an identifier.

@item ( )
Parentheses are used for grouping and to notate lists
(@ref{Pairs and lists}).

@item '
The single quote character is used to indicate literal data (@ref{Literal expressions}).

@item `
The backquote character is used to indicate almost-constant
data (@ref{Quasiquotation}).

@item , ,@@
The character comma and the sequence comma at-sign are used in conjunction
with backquote (@ref{Quasiquotation}).

@item "
The double quote character is used to delimit strings (@ref{Strings}).

@item \
Backslash is used in the syntax for character constants
(@ref{Characters}) and as an escape character within string
constants (@ref{Strings}).

@item [ ] @{ @}
Left and right square brackets and curly braces
are reserved for possible future extensions to the language.

@item #
Sharp sign is used for a variety of purposes depending on
the character that immediately follows it:

@item #t #f
These are the boolean constants (@ref{Booleans}).

@item #\
This introduces a character constant (@ref{Characters}).

@item #(
This introduces a vector constant (@ref{Vectors}).  Vector
constants are terminated by @samp{)} .

@item #e #i #b #o #d #x
These are used in the notation for numbers (@ref{Syntax of numerical constants}).

@end table

@c @page
@node Basic concepts, Expressions, Lexical conventions, Top
@chapter Basic concepts

@menu
* Variables and regions::
* True and false::
* External representations::
* Disjointness of types::
* Storage model::
@end menu

@node Variables and regions, True and false, Basic concepts, Basic concepts
@section Variables and regions

Any identifier that is not a syntactic keyword
@cindex keyword
(see @ref{Identifiers}) may be used as a variable.
@cindex syntactic keyword
@cindex identifier
@cindex @w{variable}
A variable may name a location where a value can be stored.  A variable
that does so is said to be @emph{bound} to the location.  The set of all
visible bindings
@cindex @w{binding}
in effect at some point in a program is known as the @emph{environment}
in effect at that point.  The value stored in the location to which a
variable is bound is called the variable's value.  By abuse of
terminology, the variable is sometimes said to name the value or to be
bound to the value.  This is not quite accurate, but confusion rarely
results from this practice.

@ignore
todo
Define ``assigned'' and ``unassigned'' perhaps?
@end ignore
@ignore
todo
In programs without side effects, one can safely pretend that the
variables are bound directly to the arguments.  Or:
In programs without @code{set!}, one can safely pretend that the
@findex set!
variable is bound directly to the value.
@end ignore

@c vest
Certain expression types are used to create new locations and to bind
variables to those locations.  The most fundamental of these
@emph{binding constructs}
@cindex @w{binding construct}
@cindex lambda expression
is the lambda expression, because all other binding constructs can be
explained in terms of lambda expressions.  The other binding constructs
are @code{let}, @code{let*}, @code{letrec}, and @code{do} expressions
(see @ref{Lambda expressions}, @ref{Binding constructs}, and
@ref{Iteration}).
@findex letrec
@findex let*
@findex let
@findex do

@c Note: internal definitions not mentioned here.
@c vest
Like Algol and Pascal, and unlike most other dialects of Lisp except for
Common Lisp, Scheme is a statically scoped language with block
structure.  To each place where a variable is bound in a program there
corresponds a @dfn{region} of the program text within which the binding
is effective.  The region is determined by the particular binding
construct that establishes the binding; if the binding is established by
a lambda expression, for example, then its region is the entire lambda
expression.  Every reference to or assignment of a variable refers to
the binding of the variable that established the innermost of the
regions containing the use.  If there is no binding of the variable
whose region contains the use, then the use refers to the binding for
the variable in the top level environment, if any (section
@ref{Standard procedures}); if there is no binding for the identifier,
it is said to be @dfn{unbound}.
@cindex @w{bound}
@cindex top level environment

@ignore
todo
Mention that some implementations have multiple top level
environments?
@end ignore

@ignore
todo
Pitman sez: needs elaboration in case of @code{(let ...)}
@end ignore

@ignore
todo
Pitman asks: say something about vars created after scheme starts?
@code{(define x 3) (define (f) x) (define (g) y) (define y 4)}
Clinger replies: The language was explicitly
designed to permit a view in which no variables are created after
Scheme starts.  In files, you can scan out the definitions beforehand.
I think we're agreed on the principle that interactive use should
approximate that behavior as closely as possible, though we don't yet
agree on which programming environment provides the best
approximation.
@end ignore

@node True and false, External representations, Variables and regions, Basic concepts
@section True and false

Any Scheme value can be used as a boolean value for the purpose of a
conditional test.  As explained in @ref{Booleans}, all
values count as true in such a test except for @code{#f}.
@c  and possibly the empty list.
@c  The only value that is guaranteed to count as
@c  false is @code{#f}.  It is explicitly unspecified whether the empty list
@c  counts as true or as false.
This report uses the word ``true'' to refer to any
Scheme value that counts as true, and the word ``false'' to refer to
@code{#f}.
@cindex @w{true}
@cindex @w{false}

@emph{Note:}  In some implementations the empty list also counts as
false instead of true.
@c end note

@ignore
todo
Bartley: tighten this up.
@end ignore

@node External representations, Disjointness of types, True and false, Basic concepts
@section External representations

An important concept in Scheme (and Lisp) is that of the @emph{external
representation} of an object as a sequence of characters.  For example,
an external representation of the integer 28 is the sequence of
characters ``@code{28}'', and an external representation of a list consisting
of the integers 8 and 13 is the sequence of characters ``@code{(8 13)}''.

The external representation of an object is not necessarily unique.  The
integer 28 also has representations ``@code{#e28.000}'' and
``@code{#x1c}'', and the list in the previous paragraph also has the
representations ``@code{( 08 13 )}'' and ``@code{(8 .@: (13 .@: ()))}''
(see @ref{Pairs and lists}).

Many objects have standard external representations, but some, such as
procedures, do not have standard representations (although particular
implementations may define representations for them).

An external representation may be written in a program to obtain the
corresponding object (see @code{quote}, @ref{Literal expressions}).
@findex quote

External representations can also be used for input and output.  The
procedure @code{read} (@ref{Input}) parses external
@findex read
representations, and the procedure @code{Output} (@ref{Output})
@findex write
generates them.  Together, they provide an elegant and powerful
input/output facility.

Note that the sequence of characters ``@code{(+ 2 6)}'' is @emph{not} an
external representation of the integer 8, even though it @emph{is} an
expression evaluating to the integer 8; rather, it is an external
representation of a three-element list, the elements of which are the symbol
@code{+} and the integers 2 and 6.  Scheme's syntax has the property that
any sequence of characters that is an expression is also the external
representation of some object.  This can lead to confusion, since it may
not be obvious out of context whether a given sequence of characters is
intended to denote data or program, but it is also a source of power,
since it facilitates writing programs such as interpreters and
compilers that treat programs as data (or vice versa).

The syntax of external representations of various kinds of objects
accompanies the description of the primitives for manipulating the
objects in the appropriate sections of @ref{Standard procedures}.

@node Disjointness of types, Storage model, External representations, Basic concepts
@section Disjointness of types

No object satisfies more than one of the following predicates:

@lisp
boolean?          pair?
symbol?           number?
char?             string?
vector?           procedure?
@end lisp

These predicates define the types @emph{boolean}, @emph{pair},
@emph{symbol}, @emph{number}, @emph{char} (or @emph{character}),
@emph{string}, @emph{vector}, and @emph{procedure}.
@cindex @w{type}

@node Storage model,  , Disjointness of types, Basic concepts
@section Storage model

Variables and objects such as pairs, vectors, and strings implicitly
denote locations
@cindex @w{location}
or sequences of locations.  A string, for
example, denotes as many locations as there are characters in the string.
(These locations need not correspond to a full machine word.) A new value may be
stored into one of these locations using the @code{string-set!} procedure, but
the string continues to denote the same locations as before.

An object fetched from a location, by a variable reference or by
a procedure such as @code{car}, @code{vector-ref}, or @code{string-ref}, is
@findex string-ref
@findex vector-ref
@findex car
equivalent in the sense of @code{eqv?} (section
@ref{Equivalence predicates})
@findex eqv?
to the object last stored in the location before the fetch.

Every location is marked to show whether it is in use.
No variable or object ever refers to a location that is not in use.
Whenever this report speaks of storage being allocated for a variable
or object, what is meant is that an appropriate number of locations are
chosen from the set of locations that are not in use, and the chosen
locations are marked to indicate that they are now in use before the variable
or object is made to denote them.

In many systems it is desirable for constants
@cindex constant
(i.e. the values of
literal expressions) to reside in read-only-memory.  To express this, it is
convenient to imagine that every object that denotes locations is associated
with a flag telling whether that object is mutable
@cindex mutable
or immutable.
@cindex immutable
The constants and the strings returned by @code{symbol->string} are
@findex symbol->string
then the immutable objects, while all objects created by the other
procedures listed in this report are mutable.  It is an error to attempt
to store a new value into a location that is denoted by an immutable
object.

@c @page
@node Expressions, Program structure, Basic concepts, Top
@chapter Expressions

A Scheme expression is a construct that returns a value, such as a
variable reference, literal, procedure call, or conditional.

Expression types are categorized as @emph{primitive} or @emph{derived}.
Primitive expression types include variables and procedure calls.
Derived expression types are not semantically primitive, but can instead
be explained in terms of the primitive constructs as in
@ref{Formal derived expression types}.  They are redundant in the strict sense of
the word, but they capture common patterns of usage, and are therefore
provided as convenient abbreviations.

@menu
* Primitive expression types::
* Derived expression types::
@end menu

@node Primitive expression types, Derived expression types, Expressions, Expressions
@section Primitive expression types

@menu
* Variable references::
* Literal expressions::
* Procedure calls::
* Lambda expressions::
* Conditionals:Primitive Conditionals
* Assignments::
@end menu

@node Variable references, Literal expressions, Primitive expression types, Primitive expression types
@subsection Variable references

@deffn {essential syntax} @r{<variable>}

An expression consisting of a variable
@cindex variable

(@ref{Variables and regions}) is a variable reference.  The value of
the variable reference is the value stored in the location to which the
variable is bound.  It is an error to reference an
unbound
@cindex unbound
variable.

@lisp
(define x 28)
x                           @result{}  28
@end lisp
@end deffn

@node Literal expressions, Procedure calls, Variable references, Primitive expression types
@subsection Literal expressions

@deffn {essential syntax} quote @r{<datum>}
@deffnx {essential syntax} '@r{<datum>}
@deffnx {essential syntax} @r{<constant>}

@code{(quote @r{<datum>})} evaluates to @r{<datum>}.
@vindex @w{'}
@r{<Datum>} may be any external representation of a Scheme object (see
@ref{External representations}).  This notation is used to
include literal constants in Scheme code.
@cindex constant

@lisp
(quote a)                   @result{}  a
(quote #(a b c))            @result{}  #(a b c)
(quote (+ 1 2))             @result{}  (+ 1 2)
@end lisp

@code{(quote @r{<datum>})} may be abbreviated as
'@r{<datum>}.  The two notations are equivalent in all
respects.

@lisp
'a                          @result{}  a
'#(a b c)                   @result{}  #(a b c)
'()                         @result{}  ()
'(+ 1 2)                    @result{}  (+ 1 2)
'(quote a)                  @result{}  (quote a)
''a                         @result{}  (quote a)
@end lisp

Numerical constants, string constants, character constants, and boolean
constants evaluate ``to themselves''; they need not be quoted.

@lisp
'"abc"                      @result{}  "abc"
"abc"                       @result{}  "abc"
'145932                     @result{}  145932
145932                      @result{}  145932
'#t                         @result{}  #t
#t                          @result{}  #t
@end lisp

As noted in @ref{Storage model}, it is an error to alter a constant
(i.e. the value of a literal expression) using a mutation procedure like
@code{set-car!} or @code{string-set!}.
@findex string-set!
@findex set-car!
@cindex constant

@end deffn

@node Procedure calls, Lambda expressions, Literal expressions, Primitive expression types
@subsection Procedure calls

@deffn {essential syntax} @r{<operator>} @r{<operand 1>} @dots{}

A procedure call is written by simply enclosing in parentheses
expressions for the procedure to be called and the arguments to be
passed to it.  The operator and operand expressions are evaluated (in an
unspecified order) and the resulting procedure is passed the resulting
arguments.
@cindex @w{call}
@cindex @w{procedure call}

@lisp
(+ 3 4)                     @result{}  7
((if #f + *) 3 4)           @result{}  12
@end lisp

A number of procedures are available as the values of variables in the
initial environment; for example, the addition and multiplication
procedures in the above examples are the values of the variables
@code{+} and @code{*}.
@findex +
@findex *
New procedures are created by evaluating lambda expressions (see section
@ref{Lambda expressions}).
@ignore
todo
At Friedman's reuest, flushed mention of other ways.
@end ignore
@c  or definitions (see @ref{define}).

Procedure calls are also called @emph{combinations}.
@cindex @w{combination}

@emph{Note:}  In contrast to other dialects of Lisp, the order of
evaluation is unspecified, and the operator expression and the operand
expressions are always evaluated with the same evaluation rules.
@c end note

@emph{Note:}  Although the order of evaluation is otherwise unspecified, the effect of
any concurrent evaluation of the operator and operand expressions is
constrained to be consistent with some sequential order of evaluation.
The order of evaluation may be chosen differently for each procedure call.
@c end note

@emph{Note:}  In many dialects of Lisp, the empty combination,
@code{()}, is a legitimate expression.  In Scheme, combinations must
have at
least one subexpression, so @code{()} is not a syntactically valid
expression.
@ignore
todo
Dybvig: ``it should be obvious from the syntax.''
@end ignore

@c end note

@ignore
todo
Freeman:
I think an explanation as to why evaluation order is not specified
should be included.  It should not include any reference to parallel
evaluation.  Does any existing compiler generate better code because
the evaluation order is unspecified?  Clinger: yes: T3, MacScheme v2,
probably MIT Scheme and Chez Scheme.  But that's not the main reason
for leaving the order unspecified.
@end ignore

@end deffn

@node Lambda expressions, Primitive Conditionals, Procedure calls, Primitive expression types
@subsection Lambda expressions

@deffn {essential syntax} lambda @r{<formals>} @r{<body>}

@emph{Syntax:}  @r{<Formals>} should be a formal arguments list as described below,
and @r{<body>} should be a sequence of one or more expressions.

@emph{Semantics:}  @c vest
A lambda expression evaluates to a procedure.  The environment in
effect when the lambda expression was evaluated is remembered as part of the
procedure.  When the procedure is later called with some actual
arguments, the environment in which the lambda expression was evaluated will
be extended by binding the variables in the formal argument list to
fresh locations, the corresponding actual argument values will be stored
in those locations, and the expressions in the body of the lambda expression
will be evaluated sequentially in the extended environment.  The result
of the last expression in the body will be returned as the result of
the procedure call.

@lisp
(lambda (x) (+ x x))        @result{}  @emph{a procedure}
((lambda (x) (+ x x)) 4)    @result{}  8

(define reverse-subtract
  (lambda (x y) (- y x)))
(reverse-subtract 7 10)     @result{}  3

(define add4
  (let ((x 4))
    (lambda (y) (+ x y))))
(add4 6)                    @result{}  10
@end lisp

@r{<Formals>} should have one of the following forms:

@itemize @bullet
@item @code{(@r{<variable 1>} @dots{})}:
The procedure takes a fixed number of arguments; when the procedure is
called, the arguments will be stored in the bindings of the
corresponding variables.

@item @r{<variable>}:
The procedure takes any number of arguments; when the procedure is
called, the sequence of actual arguments is converted into a newly
allocated list, and the list is stored in the binding of the
@r{<variable>}.

@item @code{(@r{<variable 1>} @dots{} @r{<variable n-1>} . @r{<variable n>})}:
If a space-delimited period precedes the last variable, then
the value stored in the binding of the last variable will be a
newly allocated
list of the actual arguments left over after all the other actual
arguments have been matched up against the other formal arguments.
@end itemize

It is an error for a @r{<variable>} to appear more than once in
@r{<formals>}.

@lisp
((lambda x x) 3 4 5 6)      @result{}  (3 4 5 6)
((lambda (x y . z) z)
 3 4 5 6)                   @result{}  (5 6)
@end lisp

Each procedure created as the result of evaluating a lambda expression
is tagged with a storage location, in order to make @code{eqv?} and
@code{eq?} work on procedures (see @ref{Equivalence predicates}).
@findex eqv?
@findex eq?

@end deffn

@node Primitive Conditionals, Assignments, Lambda expressions, Primitive expression types
@subsection Conditionals

@deffn {essential syntax} if @r{<test>} @r{<consequent>} @r{<alternate>}
@deffnx {syntax} if @r{<test>} @r{<consequent>}
@c \/ if hyper = italic

@emph{Syntax:}  @r{<Test>}, @r{<consequent>}, and @r{<alternate>} may be arbitrary
expressions.

@emph{Semantics:}  An @code{if} expression is evaluated as follows: first,
@findex if
@r{<test>} is evaluated.  If it yields a true value
@cindex true
(see @ref{Booleans}), then @r{<consequent>} is evaluated
and its value is returned.  Otherwise @r{<alternate>} is evaluated and
its value is returned.  If @r{<test>} yields a false value and no
@r{<alternate>} is specified, then the result of the expression is
unspecified.

@lisp
(if (> 3 2) 'yes 'no)       @result{}  yes
(if (> 2 3) 'yes 'no)       @result{}  no
(if (> 3 2)
    (- 3 2)
    (+ 3 2))                @result{}  1
@end lisp

@end deffn

@node Assignments,  , Primitive Conditionals, Primitive expression types
@subsection Assignments

@deffn {essential syntax} set! @r{<variable>} @r{<expression>}

@r{<Expression>} is evaluated, and the resulting value is stored in
the location to which @r{<variable>} is bound.  @r{<Variable>} must
be bound either in some region
@cindex region
enclosing the @code{set!} expression
@findex set!
or at top level.  The result of the @code{set!} expression is
@findex set!
unspecified.

@lisp
(define x 2)
(+ x 1)                     @result{}  3
(set! x 4)                  @result{}  @emph{unspecified}
(+ x 1)                     @result{}  5
@end lisp

@end deffn

@node Derived expression types,  , Primitive expression types, Expressions
@section Derived expression types

For reference purposes, @ref{Formal derived expression types} gives rewrite rules
that will convert constructs described in this section into the
primitive constructs described in the previous section.

@menu
* Conditionals::
* Binding constructs::
* Sequencing::
* Iteration::
* Delayed evaluation::
* Quasiquotation::
@end menu

@node Conditionals, Binding constructs, Derived expression types, Derived expression types
@subsection Conditionals

@deffn {essential syntax} cond @r{<clause 1>} @r{<clause 2>} @dots{}

@emph{Syntax:}  Each @r{<clause>} should be of the form
@lisp
(@r{<test>} @r{<expression>} @dots{})
@end lisp
where @r{<test>} is any expression.  The last @r{<clause>} may be
an ``else clause,'' which has the form
@lisp
(else @r{<expression 1>} @r{<expression 2>} @dots{})@r{.}
@end lisp

@vindex @w{else}
@vindex @w{=>}

@emph{Semantics:}  A @code{cond} expression is evaluated by evaluating the @r{<test>}
@findex cond
expressions of successive @r{<clause>}s in order until one of them
evaluates to a true value
@cindex true
(see @ref{Booleans}).  When a @r{<test>} evaluates to a
true value, then the remaining @r{<expression>}s in its @r{<clause>} are
evaluated in order, and the result of the last @r{<expression>} in the
@r{<clause>} is returned as the result of the entire @code{cond}
@findex cond
expression.  If the selected @r{<clause>} contains only the @r{<test>}
and no @r{<expression>}s, then the value of the @r{<test>} is returned
as the result.  If all @r{<test>}s evaluate to false values, and there
is no else clause, then the result of the conditional expression is
unspecified; if there is an else clause, then its @r{<expression>}s are
evaluated, and the value of the last one is returned.

@lisp
(cond ((> 3 2) 'greater)
      ((< 3 2) 'less))      @result{}  greater

(cond ((> 3 3) 'greater)
      ((< 3 3) 'less)
      (else 'equal))        @result{}  equal
@end lisp

Some implementations support an alternative @r{<clause>} syntax,
@code{(@r{<test>} => @r{<recipient>})}, where @r{<recipient>} is an
expression.  If @r{<test>} evaluates to a true value, then
@r{<recipient>} is evaluated.  Its value must be a procedure of one
argument; this procedure is then invoked on the value of the
@r{<test>}.

@lisp
(cond ((assv 'b '((a 1) (b 2))) => cadr)
      (else @code{#f}))     @result{}  2
@end lisp

@end deffn

@deffn {essential syntax} case @r{<key>} @r{<clause 1>} @r{<clause 2>} @dots{}

@emph{Syntax:}  @r{<Key>} may be any expression.  Each @r{<clause>} should have
the form
@lisp
((@r{<datum 1>} @dots{}) @r{<expression 1>} @r{<expression 2>} @dots{})@r{,}
@end lisp
where each @r{<datum>} is an external representation of some object.
All the @r{<datum>}s must be distinct.
The last @r{<clause>} may be an ``else clause,'' which has the form
@lisp
(else @r{<expression 1>} @r{<expression 2>} @dots{})@r{.}
@end lisp

@vindex else

@emph{Semantics:}  A @code{case} expression is evaluated as follows.  @r{<Key>} is
@findex case
evaluated and its result is compared against each @r{<datum>}.  If the
result of evaluating @r{<key>} is equivalent (in the sense of
@code{eqv?}; see @ref{Equivalence predicates}) to a @r{<datum>}, then the
@findex eqv?
expressions in the corresponding @r{<clause>} are evaluated from left
to right and the result of the last expression in the @r{<clause>} is
returned as the result of the @code{case} expression.  If the result of
@findex case
evaluating @r{<key>} is different from every @r{<datum>}, then if
there is an else clause its expressions are evaluated and the
result of the last is the result of the @code{case} expression;
otherwise
@findex case
the result of the @code{case} expression is unspecified.
@findex case

@lisp
(case (* 2 3)
  ((2 3 5 7) 'prime)
  ((1 4 6 8 9) 'composite)) @result{}  composite
(case (car '(c d))
  ((a) 'a)
  ((b) 'b))                 @result{}  @emph{unspecified}
(case (car '(c d))
  ((a e i o u) 'vowel)
  ((w y) 'semivowel)
  (else 'consonant))        @result{}  consonant
@end lisp

@end deffn

@deffn {essential syntax} and @r{<test 1>} @dots{}

The @r{<test>} expressions are evaluated from left to right, and the
value of the first expression that evaluates to a false value (see
@ref{Booleans}) is returned.  Any remaining expressions
are not evaluated.  If all the expressions evaluate to true values, the
value of the last expression is returned.  If there are no expressions
then @code{#t} is returned.

@lisp
(and (= 2 2) (> 2 1))       @result{}  #t
(and (= 2 2) (< 2 1))       @result{}  #f
(and 1 2 'c '(f g))         @result{}  (f g)
(and)                       @result{}  #t
@end lisp

@end deffn

@deffn {essential syntax} or @r{<test 1>} @dots{}

The @r{<test>} expressions are evaluated from left to right, and the value of the
first expression that evaluates to a true value (see
@ref{Booleans}) is returned.  Any remaining expressions
are not evaluated.  If all expressions evaluate to false values, the
value of the last expression is returned.  If there are no
expressions then @code{#f} is returned.

@lisp
(or (= 2 2) (> 2 1))        @result{}  #t
(or (= 2 2) (< 2 1))        @result{}  #t
(or #f #f #f)               @result{}  #f
(or (memq 'b '(a b c))
    (/ 3 0))                @result{}  (b c)
@end lisp

@end deffn

@node Binding constructs, Sequencing, Conditionals, Derived expression types
@subsection Binding constructs

The three binding constructs @code{let}, @code{let*}, and @code{letrec}
@findex let
@findex let*
@findex letrec
give Scheme a block structure, like Algol 60.  The syntax of the three
constructs is identical, but they differ in the regions
@cindex region
they establish
for their variable bindings.  In a @code{let} expression, the initial
@findex let
values are computed before any of the variables become bound; in a
@code{let*} expression, the bindings and evaluations are performed
@findex let*
sequentially; while in a @code{letrec} expression, all the bindings are
in
@findex letrec
effect while their initial values are being computed, thus allowing
mutually recursive definitions.

@deffn {essential syntax} let @r{<bindings>} @r{<body>}

@emph{Syntax:}  @r{<Bindings>} should have the form
@lisp
((@r{<variable 1>} @r{<init 1>}) @dots{})@r{,}
@end lisp
where each @r{<init>} is an expression, and @r{<body>} should be a
sequence of one or more expressions.  It is
an error for a @r{<variable>} to appear more than once in the list of variables
being bound.

@emph{Semantics:}  The @r{<init>}s are evaluated in the current environment (in some
unspecified order), the @r{<variable>}s are bound to fresh locations
holding the results, the @r{<body>} is evaluated in the extended
environment, and the value of the last expression of @r{<body>} is
returned.  Each binding of a @r{<variable>} has @r{<body>} as its
region.
@cindex region

@lisp
(let ((x 2) (y 3))
  (* x y))                  @result{}  6

(let ((x 2) (y 3))
  (let ((x 7)
        (z (+ x y)))
    (* z x)))               @result{}  35
@end lisp

See also named @code{let}, @ref{Iteration}.
@findex let

@end deffn

@deffn {syntax} let* @r{<bindings>} @r{<body>}

@emph{Syntax:}  @r{<Bindings>} should have the form
@lisp
((@r{<variable 1>} @r{<init 1>}) @dots{})@r{,}
@end lisp
and @r{<body>} should be a sequence of
one or more expressions.

@emph{Semantics:}  @code{Let*} is similar to @code{let}, but the bindings are performed
@findex let
@findex let*
sequentially from left to right, and the region
@cindex region
of a binding indicated
by @code{(@r{<variable>} @r{<init>})} is that part of the @code{let*}
@findex let*
expression to the right of the binding.  Thus the second binding is done
in an environment in which the first binding is visible, and so on.

@lisp
(let ((x 2) (y 3))
  (let* ((x 7)
         (z (+ x y)))
    (* z x)))               @result{}  70
@end lisp

@end deffn

@deffn {essential syntax} letrec @r{<bindings>} @r{<body>}

@emph{Syntax:}  @r{<Bindings>} should have the form
@lisp
((@r{<variable 1>} @r{<init 1>}) @dots{})@r{,}
@end lisp
and @r{<body>} should be a sequence of
one or more expressions. It is an error for a @r{<variable>} to appear more
than once in the list of variables being bound.

@emph{Semantics:}  The @r{<variable>}s are bound to fresh locations
holding undefined values, the @r{<init>}s are evaluated in the resulting
environment (in some unspecified order), each @r{<variable>} is assigned
to the result of the corresponding @r{<init>}, the @r{<body>} is
evaluated in the resulting environment, and the value of the last
expression in @r{<body>} is returned.  Each binding of a @r{<variable>}
has the entire @code{letrec} expression as its region , making it
@findex letrec
possible to define mutually recursive procedures.
@cindex region

@lisp
@c (letrec ((x 2) (y 3))
@c   (letrec ((foo (lambda (z) (+ x y z))) (x 7))
@c     (foo 4)))            @result{}  14

(letrec ((even?
          (lambda (n)
            (if (zero? n)
                #t
                (odd? (- n 1)))))
         (odd?
          (lambda (n)
            (if (zero? n)
                #f
                (even? (- n 1))))))
  (even? 88))
                            @result{}  #t
@end lisp

One restriction on @code{letrec} is very important: it must be possible
@findex letrec
to evaluate each @r{<init>} without assigning or referring to the value of any
@r{<variable>}.  If this restriction is violated, then it is an error.  The
restriction is necessary because Scheme passes arguments by value rather than by
name.  In the most common uses of @code{letrec}, all the @r{<init>}s are
@findex letrec
lambda expressions and the restriction is satisfied automatically.

@ignore
todo
use or uses?  --- Jinx.
@end ignore

@end deffn

@node Sequencing, Iteration, Binding constructs, Derived expression types
@subsection Sequencing

@deffn {essential syntax} begin @r{<expression 1>} @r{<expression 2>} @dots{}

The @r{<expression>}s are evaluated sequentially from left to right,
and the value of the last @r{<expression>} is returned.  This
expression type is used to sequence side effects such as input and
output.

@lisp
(define x 0)

(begin (set! x 5)
       (+ x 1))             @result{}  6

(begin (display "4 plus 1 equals ")
       (display (+ 4 1)))   @result{}  @emph{unspecified}
        @emph{and prints}  4 plus 1 equals 5
@end lisp

@emph{Note:}  @sc{[SICP]} uses the keyword @code{sequence} instead of @code{begin}.
@findex begin
@findex sequence
@c end note

@end deffn

@node Iteration, Delayed evaluation, Sequencing, Derived expression types
@subsection Iteration

@deffn {syntax} do @r{<bindings>} @r{<clause>} @r{<body>}

@emph{Syntax:}  @r{<Bindings>} should have the form
@lisp
((@r{<variable 1>} @r{<init 1>} @r{<step 1>}) @dots{})@r{,}
@end lisp
@r{<clause>} should be of the form
@lisp
(@r{<test>} @r{<expression>} @dots{})@r{,}
@end lisp
and @r{<body>} should be a sequence of one or more expressions.

@code{Do} is an iteration construct.  It specifies a set of variables to
be bound, how they are to be initialized at the start, and how they are
to be updated on each iteration.  When a termination condition is met,
the loop exits with a specified result value.

@code{Do} expressions are evaluated as follows:
@findex do
The @r{<init>} expressions are evaluated (in some unspecified order),
the @r{<variable>}s are bound to fresh locations, the results of the
@r{<init>} expressions are stored in the bindings of the
@r{<variable>}s, and then the iteration phase begins.

@c vest
Each iteration begins by evaluating @r{<test>}; if the result is
false (see @ref{Booleans}), then the @r{<command>}
expressions are evaluated in order for effect, the @r{<step>}
expressions are evaluated in some unspecified order, the
@r{<variable>}s are bound to fresh locations, the results of the
@r{<step>}s are stored in the bindings of the
@r{<variable>}s, and the next iteration begins.

@c vest
If @r{<test>} evaluates to a true value, then the
@r{<expression>}s are evaluated from left to right and the value of
the last @r{<expression>} is returned as the value of the @code{do}
@findex do
expression.  If no @r{<expression>}s are present, then the value of
the @code{do} expression is unspecified.
@findex do

@c vest
The region
@cindex region
of the binding of a @r{<variable>} consists of the entire @code{do}
@findex do
expression except for the @r{<init>}s.  It is an error for a
@r{<variable>} to appear more than once in the list of @code{do}
@findex do
variables.

@c vest
A @r{<step>} may be omitted, in which case the effect is the
same as if @code{(@r{<variable>} @r{<init>} @r{<variable>})} had
been written instead of @code{(@r{<variable>} @r{<init>})}.

@lisp
(do ((vec (make-vector 5))
     (i 0 (+ i 1)))
    ((= i 5) vec)
  (vector-set! vec i i))    @result{}  #(0 1 2 3 4)

(let ((x '(1 3 5 7 9)))
  (do ((x x (cdr x))
       (sum 0 (+ sum (car x))))
      ((null? x) sum)))     @result{}  25
@end lisp

@end deffn

@deffn syntax let @r{<variable>} @r{<bindings>} @r{<body>}

@c label{Iteration}
Some implementations of Scheme permit a variant on the syntax of
@code{let} called ``named @code{let}'' which provides a more general
@findex let
@findex let
looping construct than @code{do}, and may also be used to express
@findex do
recursions.

Named @code{let} has the same syntax and semantics as ordinary
@findex let
@code{let} except that @r{<variable>} is bound within @r{<body>} to a
procedure whose formal arguments are the bound variables and whose body
is @r{<body>}.  Thus the execution of @r{<body>} may be repeated by
invoking the procedure named by @r{<variable>}.

@c                                               |  <-- right margin
@lisp
(let loop ((numbers '(3 -2 1 6 -5))
           (nonneg '())
           (neg '()))
  (cond ((null? numbers) (list nonneg neg))
        ((>= (car numbers) 0)
         (loop (cdr numbers)
               (cons (car numbers) nonneg)
               neg))
        ((< (car numbers) 0)
         (loop (cdr numbers)
               nonneg
               (cons (car numbers) neg)))))
                            @result{}  ((6 1 3) (-5 -2))
@end lisp

@end deffn

@node Delayed evaluation, Quasiquotation, Iteration, Derived expression types
@subsection Delayed evaluation
@c label{Delayed evaluation}

@deffn {syntax} delay @r{<expression>}

@ignore
todo
Fix.
@end ignore

The @code{delay} construct is used together with the
procedure @code{force} to
@findex force
implement @dfn{lazy evaluation} or @dfn{call by need}.
@code{(delay @r{<expression>})} returns an object called a
@dfn{promise} which at some point in the future may be asked (by
the @code{force} procedure)
@ignore
todo
Bartley's white lie; OK?
@end ignore
to evaluate @r{<expression>} and deliver the resulting value.

See the description of @code{force} (@ref{Control features}) for a
@findex force
more complete description of @code{delay}.

@end deffn

@node Quasiquotation,  , Delayed evaluation, Derived expression types
@subsection Quasiquotation
@c label{Quasiquotation}

@deffn {essential syntax} quasiquote @r{<template>}
@deffnx {essential syntax} ` @r{<template>}

``Backquote'' or ``quasiquote''
@cindex backquote
expressions are useful
for constructing a list or vector structure when most but not all of the
desired structure is known in advance.  If no
commas
@cindex comma
appear within the @r{<template>}, the result of evaluating
@code{`@r{<template>}} is equivalent to the result of evaluating
@code{'@r{<template>}}.  If a comma
@vindex @w{,}
appears within the
@r{<template>}, however, the expression following the comma is
evaluated (``unquoted'') and its result is inserted into the structure
instead of the comma and the expression.  If a comma appears followed
immediately by an at-sign (@@),
@cindex at-sign
then the following
expression must evaluate to a list; the opening and closing parentheses
of the list are then ``stripped away'' and the elements of the list are
inserted in place of the comma at-sign expression sequence.

@c  struck: "(in the sense of @code{equal?})" after "equivalent"
@findex equal?

@lisp
`(list ,(+ 1 2) 4)          @result{}  (list 3 4)
(let ((name 'a)) `(list ,name ',name))
                            @result{}  (list a (quote a))
`(a ,(+ 1 2) ,@@(map abs '(4 -5 6)) b)
                            @result{}  (a 3 4 5 6 b)
`((@code{foo} ,(- 10 3)) ,@@(cdr '(c)) . ,(car '(cons)))
@findex foo
                            @result{}  ((foo 7) . cons)
`#(10 5 ,(sqrt 4) ,@@(map sqrt '(16 9)) 8)
                            @result{}  #(10 5 2 4 3 8)
@end lisp

Quasiquote forms may be nested.  Substitutions are made only for
unquoted components appearing at the same nesting level
as the outermost backquote.  The nesting level increases by one inside
each successive quasiquotation, and decreases by one inside each
unquotation.

@lisp
`(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f)
                            @result{}  (a `(b ,(+ 1 2) ,(foo 4 d) e) f)
(let ((name1 'x)
      (name2 'y))
  `(a `(b ,,name1 ,',name2 d) e))
                            @result{}  (a `(b ,x ,'y d) e)
@end lisp

@vindex @w{`}
The notations @code{`@r{<template>}} and
@code{(quasiquote @r{<template>})} are identical in all respects.
@code{,@r{<expression>}} is identical to @code{(unquote
@r{<expression>})}, and @code{,@r{<expression>}} is identical to
@code{(unquote-splicing @r{<expression>})}.  The external syntax
generated by @code{write} for two-element lists whose
@findex write
car is one of these symbols may vary between implementations.


@lisp
(quasiquote (list (unquote (+ 1 2)) 4))
                            @result{}  (list 3 4)
'(quasiquote (list (unquote (+ 1 2)) 4))
                            @result{}  `(list ,(+ 1 2) 4)
     @emph{i.e.,} (quasiquote (list (unquote (+ 1 2)) 4))
@end lisp

Unpredictable behavior can result if any of the symbols
@code{quasiquote}, @code{unquote}, or @code{unquote-splicing}
@findex unquote-splicing
@findex unquote
appear in
@findex quasiquote
positions within a @r{<template>} otherwise than as described above.

@end deffn

@node Program structure, Standard procedures, Expressions, Top
@chapter Program structure
@c label{Program structure}

@menu
* Programs::
* Definitions::
@end menu

@node Programs, Definitions, Program structure, Program structure
@section Programs

A Scheme program consists of a sequence of expressions and definitions.
Expressions are described in @ref{Expressions};
definitions are the subject of the rest of the present chapter.

Programs are typically stored in files or entered interactively to a
running Scheme system, although other paradigms are possible;
questions of user interface lie outside the scope of this report.
(Indeed, Scheme would still be useful as a notation for expressing
computational methods even in the absence of a mechanical
implementation.)

Definitions occurring at the top level of a program can be interpreted
declaratively.  They cause bindings to be created in the top level
environment.  Expressions occurring at the top level of a program are
interpreted imperatively; they are executed in order when the program is
invoked or loaded, and typically perform some kind of initialization.

@ignore
todo
Cromarty, etc.: disclaimer about top level?
@end ignore

@node Definitions,  , Programs, Program structure
@section Definitions

@menu
* Top level definitions::
* Internal definitions::
@end menu

Definitions are valid in some, but not all, contexts where expressions
are allowed.  They are valid only at the top level of a @r{<program>}
and, in some implementations, at the beginning of a @r{<body>}.
@cindex @w{definition}

A definition should have one of the following forms:
@vindex @w{define}

@itemize @bullet

@item @code{(define @r{<variable>} @r{<expression>})}

This syntax is essential.

@item @code{(define (@r{<variable>} @r{<formals>}) @r{<body>})}

This syntax is not essential.  @r{<Formals>} should be either a
sequence of zero or more variables, or a sequence of one or more
variables followed by a space-delimited period and another variable (as
in a lambda expression).  This form is equivalent to
@lisp
(define @r{<variable>}
  (lambda (@r{<formals>}) @r{<body>}))@r{.}
@end lisp

@item @code{(define (@r{<variable>} .@: @r{<formal>}) @r{<body>})}

This syntax is not essential.  @r{<Formal>} should be a single
variable.  This form is equivalent to
@lisp
(define @r{<variable>}
  (lambda @r{<formal>} @r{<body>}))@r{.}
@end lisp

@item @code{(begin @r{<definition 1>} @dots{})}

This syntax is essential.  This form is equivalent to the set of
definitions that form the body of the @code{begin}.
@findex begin

@end itemize

@node Top level definitions, Internal definitions, Definitions, Definitions
@subsection Top level definitions

At the top level of a program, a definition
@lisp
(define @r{<variable>} @r{<expression>})
@end lisp
has essentially the same effect as the assignment expression
@lisp
(set! @r{<variable>} @r{<expression>})
@findex set!
@end lisp
if @r{<variable>} is bound.  If @r{<variable>} is not bound,
however, then the definition will bind @r{<variable>} to a new
location before performing the assignment, whereas it would be an error
to perform a @code{set!} on an unbound
@findex set!
@cindex unbound
variable.

@lisp
(define add3
  (lambda (x) (+ x 3)))
(add3 3)                    @result{}  6
(define first car)
(first '(1 2))              @result{}  1
@end lisp

All Scheme implementations must support top level definitions.

Some implementations of Scheme use an initial environment in
which all possible variables are bound to locations, most of
which contain undefined values.  Top level definitions in
such an implementation are truly equivalent to assignments.

@ignore
todo
Rozas: equal time for opposition semantics?
@end ignore

@node Internal definitions,  , Top level definitions, Definitions
@subsection Internal definitions
@c label{Internal definitions}

Some implementations of Scheme permit definitions to occur at the
beginning of a @r{<body>} (that is, the body of a @code{lambda},
@code{let}, @code{let*}, @code{letrec}, or @code{define}
@findex Lambda expressions
@findex define
@findex letrec
@findex let*
expression).  Such
@findex let
definitions are known as @emph{internal definitions}
@cindex @w{internal definition}
as opposed to the top level definitions described above.
The variable defined by an internal definition is local to the
@r{<body>}.  That is, @r{<variable>} is bound rather than assigned,
and the region of the binding is the entire @r{<body>}.  For example,

@lisp
(let ((x 5))
  (define foo (lambda (y) (bar x y)))
  (define bar (lambda (a b) (+ (* a b) a)))
  (foo (+ x 3)))            @result{}  45
@end lisp

A @r{<body>} containing internal definitions can always be converted
into a completely equivalent @code{letrec} expression.  For example, the
@findex letrec
@code{let} expression in the above example is equivalent to
@findex let

@lisp
(let ((x 5))
  (letrec ((foo (lambda (y) (bar x y)))
           (bar (lambda (a b) (+ (* a b) a))))
    (foo (+ x 3))))
@end lisp

Just as for the equivalent @code{letrec} expression, it must be
@findex letrec
possible to evaluate each @r{<expression>} of every internal
definition in a @r{<body>} without assigning or referring to
the value of any @r{<variable>} being defined.

@c  Initial environment

@c @page
@node Standard procedures, Formal syntax and semantics, Program structure, Top
@chapter Standard procedures
@c label{Standard procedures}
@c label{Standard procedures}

@cindex @w{initial environment}
@cindex @w{top level environment}

This chapter describes Scheme's built-in procedures.  The initial (or
``top level'') Scheme environment starts out with a number of variables
bound to locations containing useful values, most of which are primitive
procedures that manipulate data.  For example, the variable @code{abs}
is
@findex abs
bound to (a location initially containing) a procedure of one argument
that computes the absolute value of a number, and the variable @code{+}
@findex +
is bound to a procedure that computes sums.

@menu
* Booleans::
* Equivalence predicates::
* Pairs and lists::
* Symbols::
* Numbers::
* Characters::
* Strings::
* Vectors::
* Control features::
* Input and output::
@end menu

@node Booleans, Equivalence predicates, Standard procedures, Standard procedures
@section Booleans
@c label{Booleans}

The standard boolean objects for true and false are written as
@code{#t} and @code{#f}.
@vindex #t
@vindex #f
What really matters, though, are the objects that the Scheme conditional
expressions (@code{if}, @code{cond}, @code{and}, @code{or}, @code{do})
treat as true or false.
@findex or
@findex and
@findex cond
@findex if
@findex do
@cindex true
@cindex false
The phrase ``a true value'' (or sometimes just ``true'') means any
object treated as true by the conditional expressions, and the phrase
``a false value'' (or ``false'') means any object treated as false by
the conditional expressions.

@c vest
Of all the standard Scheme values, only @code{#f}
@c  is guaranteed to count
counts as false in conditional expressions.
@c   It is not
@c  specified whether the empty list
@c @cindex empty list
@c  counts as false or as true in conditional expressions.
Except for @code{#f},
@c  and possibly the empty list,
all standard Scheme values, including @code{#t},
pairs, the empty list, symbols, numbers, strings, vectors, and procedures,
count as true.

@emph{Note:}  In some implementations the empty list counts as false, contrary
to the above.
Nonetheless a few examples in this report assume that the
empty list counts as true, as in @sc{[IEEEScheme]}.
@c end note

@c  @emph{Rationale:}  @c  For historical reasons some implementations regard @code{#f} and the
@c  empty list as the same object.  These implementations therefore cannot
@c  make the empty list count as true in conditional expressions.
@c  @c end rationale

@emph{Note:}  Programmers accustomed to other dialects of Lisp should be aware that
Scheme distinguishes both @code{#f} and the empty list from the symbol
@code{nil}.
@findex nil
@c end note

@c vest
Boolean constants evaluate to themselves, so they don't need to be quoted
in programs.

@lisp
#t                          @result{}  #t
#f                          @result{}  #f
'#f                         @result{}  #f
@end lisp

@deffn {essential procedure} not obj

@code{Not} returns @code{#t} if @var{obj} is false, and returns
@findex not
@code{#f} otherwise.

@lisp
(not #t)                    @result{}  #f
(not 3)                     @result{}  #f
(not (list 3))              @result{}  #f
(not #f)                    @result{}  #t
(not '())                   @result{}  #f
(not (list))                @result{}  #f
(not 'nil)                  @result{}  #f
@end lisp

@end deffn

@deffn {essential procedure} boolean? obj

@code{Boolean?} returns @code{#t} if @var{obj} is either @code{#t} or
@findex boolean?
@code{#f} and returns @code{#f} otherwise.

@lisp
(boolean? #f)               @result{}  #t
(boolean? 0)                @result{}  #f
(boolean? '())              @result{}  #f
@end lisp

@end deffn

@node Equivalence predicates, Pairs and lists, Booleans, Standard procedures
@section Equivalence predicates
@c label{Equivalence predicates}

A @dfn{predicate} is a procedure that always returns a boolean
value (@code{#t} or @code{#f}).  An @dfn{equivalence predicate} is
the computational analogue of a mathematical equivalence relation (it is
symmetric, reflexive, and transitive).  Of the equivalence predicates
described in this section, @code{eq?} is the finest or most
@findex eq?
discriminating, and @code{equal?} is the coarsest.  @code{Eqv?} is
@findex eqv?
@findex equal?
slightly less discriminating than @code{eq?}.
@findex eq?
@ignore
todo
Pitman doesn't like
this paragraph.  Lift the discussion from the Maclisp manual.  Explain
why there's more than one predicate.
@end ignore

@deffn {essential procedure} eqv? obj1 obj2

The @code{eqv?} procedure defines a useful equivalence relation on
objects.
@findex eqv?
Briefly, it returns @code{#t} if @var{obj1} and @var{obj2} should
normally be regarded as the same object.  This relation is left slightly
open to interpretation, but the following partial specification of
@code{eqv?} holds for all implementations of Scheme.
@findex eqv?

The @code{eqv?} procedure returns @code{#t} if:
@findex eqv?

@itemize @bullet
@item @var{obj1} and @var{obj2} are both @code{#t} or both @code{#f}.

@item @var{obj1} and @var{obj2} are both symbols and

@lisp
(string=? (symbol->string obj1)
          (symbol->string obj2))
                            @result{}  #t
@end lisp

@emph{Note:}  This assumes that neither @var{obj1} nor @var{obj2} is an ``uninterned
symbol'' as alluded to in @ref{Symbols}.  This report does
not presume to specify the behavior of @code{eqv?} on
implementation-dependent
@findex eqv?
extensions.
@c end note

@item @var{obj1} and @var{obj2} are both numbers, are numerically
equal (see @code{=}, @ref{Numbers}), and are either both
@findex =
exact or both inexact.
@cindex exact
@cindex inexact

@item @var{obj1} and @var{obj2} are both characters and are the same
character according to the @code{char=?} procedure (@ref{Characters}).
@findex char=?

@item both @var{obj1} and @var{obj2} are the empty list.

@item @var{obj1} and @var{obj2} are pairs, vectors, or strings that denote the
same locations in the store (@ref{Storage model}).

@item @var{obj1} and @var{obj2} are procedures whose location tags are
equal (@ref{Lambda expressions}).
@end itemize

The @code{eqv?} procedure returns @code{#f} if:
@findex eqv?

@itemize @bullet
@item @var{obj1} and @var{obj2} are of different types
(@ref{Disjointness of types}).

@item one of @var{obj1} and @var{obj2} is @code{#t} but the other is
@code{#f}.

@item @var{obj1} and @var{obj2} are symbols but

@lisp
(string=? (symbol->string @var{obj1})
          (symbol->string @var{obj2}))
                            @result{}  #f
@end lisp

@item one of @var{obj1} and @var{obj2} is an exact number but the other
is an inexact number.

@item @var{obj1} and @var{obj2} are numbers for which the @code{=}
@findex =
procedure returns @code{#f}.

@item @var{obj1} and @var{obj2} are characters for which the
@code{char=?}
@findex char=?
procedure returns @code{#f}.

@item one of @var{obj1} and @var{obj2} is the empty list but the other
is not.

@item @var{obj1} and @var{obj2} are pairs, vectors, or strings that denote
distinct locations.

@item @var{obj1} and @var{obj2} are procedures that would behave differently
(return a different value or have different side effects) for some arguments.

@end itemize

@lisp
(eqv? 'a 'a)                @result{}  #t
(eqv? 'a 'b)                @result{}  #f
(eqv? 2 2)                  @result{}  #t
(eqv? '() '())              @result{}  #t
(eqv? 100000000 100000000)  @result{}  #t
(eqv? (cons 1 2) (cons 1 2))@result{}  #f
(eqv? (lambda () 1)
      (lambda () 2))        @result{}  #f
(eqv? #f 'nil)              @result{}  #f
(let ((p (lambda (x) x)))
  (eqv? p p))               @result{}  #t
@end lisp

The following examples illustrate cases in which the above rules do
not fully specify the behavior of @code{eqv?}.  All that can be said
@findex eqv?
about such cases is that the value returned by @code{eqv?} must be a
@findex eqv?
boolean.

@lisp
(eqv? "" "")                @result{}  @emph{unspecified}
(eqv? '#() '#())            @result{}  @emph{unspecified}
(eqv? (lambda (x) x)
      (lambda (x) x))       @result{}  @emph{unspecified}
(eqv? (lambda (x) x)
      (lambda (y) y))       @result{}  @emph{unspecified}
@end lisp

The next set of examples shows the use of @code{eqv?} with procedures
@findex eqv?
that have local state.  @code{Gen-counter} must return a distinct
@findex gen-counter
procedure every time, since each procedure has its own internal counter.
@code{Gen-loser}, however, returns equivalent procedures each time,
since
@findex gen-loser
the local state does not affect the value or side effects of the
procedures.

@lisp
(define gen-counter
  (lambda ()
    (let ((n 0))
      (lambda () (set! n (+ n 1)) n))))
(let ((g (gen-counter)))
  (eqv? g g))               @result{}  #t
(eqv? (gen-counter) (gen-counter))
                            @result{}  #f
(define gen-loser
  (lambda ()
    (let ((n 0))
      (lambda () (set! n (+ n 1)) 27))))
(let ((g (gen-loser)))
  (eqv? g g))               @result{}  #t
(eqv? (gen-loser) (gen-loser))
                            @result{}  @emph{unspecified}

(letrec ((f (lambda () (if (eqv? f g) 'both 'f)))
         (g (lambda () (if (eqv? f g) 'both 'g)))
  (eqv? f g))
                            @result{}  @emph{unspecified}

(letrec ((f (lambda () (if (eqv? f g) 'f 'both)))
         (g (lambda () (if (eqv? f g) 'g 'both)))
  (eqv? f g))
                            @result{}  #f
@end lisp

@c  Objects of distinct types must never be regarded as the same object,
@c  except that @code{#f} and the empty list are permitted to
@c  be identical.
@c @cindex empty list

@c  @lisp
@c  (eqv? '() #f)           @result{}  @emph{unspecified}
@c  @end lisp

Since it is an error to modify constant objects (those returned by
literal expressions), implementations are permitted, though not
required, to share structure between constants where appropriate.  Thus
the value of @code{eqv?} on constants is sometimes
@findex eqv?
implementation-dependent.

@lisp
(eqv? '(a) '(a))            @result{}  @emph{unspecified}
(eqv? "a" "a")              @result{}  @emph{unspecified}
(eqv? '(b) (cdr '(a b)))    @result{}  @emph{unspecified}
(let ((x '(a)))
  (eqv? x x))               @result{}  #t
@end lisp

@emph{Rationale:}  The above definition of @code{eqv?} allows implementations latitude in
@findex eqv?
their treatment of procedures and literals:  implementations are free
either to detect or to fail to detect that two procedures or two literals
are equivalent to each other, and can decide whether or not to
merge representations of equivalent objects by using the same pointer or
bit pattern to represent both.
@c end rationale

@end deffn

@deffn {essential procedure} eq? obj1 obj2

@code{Eq?} is similar to @code{eqv?} except that in some cases it
@findex eqv?
is
@findex eq?
capable of discerning distinctions finer than those detectable by
@code{eqv?}.
@findex eqv?

@c vest
@code{Eq?} and @code{eqv?} are guaranteed to have the same
@findex eqv?
@findex eq?
behavior on symbols, booleans, the empty list, pairs, and non-empty
strings and vectors.  @code{Eq?}'s behavior on numbers and characters is
@findex eq?
implementation-dependent, but it will always return either true or
false, and will return true only when @code{eqv?} would also return
@findex eqv?
true.  @code{Eq?} may also behave differently from @code{eqv?} on
@findex eqv?
empty
@findex eq?
vectors and empty strings.

@lisp
(eq? 'a 'a)                 @result{}  #t
(eq? '(a) '(a))             @result{}  @emph{unspecified}
(eq? (list 'a) (list 'a))   @result{}  #f
(eq? "a" "a")               @result{}  @emph{unspecified}
(eq? "" "")                 @result{}  @emph{unspecified}
(eq? '() '())               @result{}  #t
(eq? 2 2)                   @result{}  @emph{unspecified}
(eq? #\A #\A)               @result{}  @emph{unspecified}
(eq? car car)               @result{}  #t
(let ((n (+ 2 3)))
  (eq? n n))                @result{}  @emph{unspecified}
(let ((x '(a)))
  (eq? x x))                @result{}  #t
(let ((x '#()))
  (eq? x x))                @result{}  #t
(let ((p (lambda (x) x)))
  (eq? p p))                @result{}  #t
@end lisp

@ignore
todo
Needs to be explained better above.  How can this be made to be
not confusing?  A table maybe?
@end ignore

@emph{Rationale:}  It will usually be possible to implement @code{eq?}
much
@findex eq?
more efficiently than @code{eqv?}, for example, as a simple pointer
@findex eqv?
comparison instead of as some more complicated operation.  One reason is
that it may not be possible to compute @code{eqv?} of two numbers in
@findex eqv?
constant time, whereas @code{eq?} implemented as pointer comparison
will
@findex eq?
always finish in constant time.  @code{Eq?} may be used like @code{eqv?}
@findex eqv?
in applications using procedures to implement objects with state since
it obeys the same constraints as @code{eqv?}.
@findex eqv?
@c end rationale

@end deffn

@deffn {essential procedure} equal? obj1 obj2

@code{Equal?} recursively compares the contents of pairs, vectors, and
@findex equal?
strings, applying @code{eqv?} on other objects such as numbers and
symbols.
@findex eqv?
A rule of thumb is that objects are generally @code{equal?} if they
print
@findex equal?
the same.  @code{Equal?} may fail to terminate if its arguments are
@findex equal?
circular data structures.

@lisp
(equal? 'a 'a)              @result{}  #t
(equal? '(a) '(a))          @result{}  #t
(equal? '(a (b) c)
        '(a (b) c))         @result{}  #t
(equal? "abc" "abc")        @result{}  #t
(equal? 2 2)                @result{}  #t
(equal? (make-vector 5 'a)
        (make-vector 5 'a)) @result{}  #t
(equal? (lambda (x) x)
        (lambda (y) y))     @result{}  @emph{unspecified}
@end lisp

@end deffn

@node Pairs and lists, Symbols, Equivalence predicates, Standard procedures
@section Pairs and lists
@c label{Pairs and lists}

A @dfn{pair} (sometimes called a @dfn{dotted pair}) is a
record structure with two fields called the car and cdr fields (for
historical reasons).  Pairs are created by the procedure @code{cons}.
@findex cons
The car and cdr fields are accessed by the procedures @code{car} and
@findex car
@code{cdr}.  The car and cdr fields are assigned by the procedures
@findex cdr
@code{set-car!} and @code{set-cdr!}.
@findex set-cdr!
@findex set-car!

Pairs are used primarily to represent lists.  A list can be defined
recursively as either the empty list
@cindex empty list
or a pair whose cdr is a list.  More precisely, the set of lists is
defined as the smallest set @var{X} such that

@itemize @bullet
@item The empty list is in @var{X}.
@item If @var{list} is in @var{X}, then any pair whose cdr field contains
      @var{list} is also in @var{X}.
@end itemize

The objects in the car fields of successive pairs of a list are the
elements of the list.  For example, a two-element list is a pair whose car
is the first element and whose cdr is a pair whose car is the second element
and whose cdr is the empty list.  The length of a list is the number of
elements, which is the same as the number of pairs.

The empty list
@cindex @w{empty list}
is a special object of its own type (it is not a pair); it has no
elements and its length is zero.

@emph{Note:}  The above definitions imply that all lists have finite length and are
terminated by the empty list.
@c end note

The most general notation (external representation) for Scheme pairs is
the ``dotted'' notation @w{@code{(@var{c1} .@: @var{c2})}} where
@var{c1} is the value of the car field and @var{c2} is the value of the
cdr field.  For example @w{@code{(4 .@: 5)}} is a pair whose car is 4
and whose cdr is 5.  Note that @w{@code{(4 .@: 5)}} is the external
representation of a pair, not an expression that evaluates to a pair.

A more streamlined notation can be used for lists: the elements of the
list are simply enclosed in parentheses and separated by spaces.  The
empty list
@cindex empty list
is written @code{()}.  For example,

@lisp
(a b c d e)
@end lisp

@noindent
and

@lisp
(a . (b . (c . (d . (e . ())))))
@end lisp

@noindent
are equivalent notations for a list of symbols.

A chain of pairs not ending in the empty list is called an
@dfn{improper list}.  Note that an improper list is not a list.
The list and dotted notations can be combined to represent
improper lists:

@lisp
(a b c . d)
@end lisp

@noindent
is equivalent to

@lisp
(a . (b . (c . d)))
@end lisp

Whether a given pair is a list depends upon what is stored in the cdr
field.  When the @code{set-cdr!} procedure is used, an object can be a
@findex set-cdr!
list one moment and not the next:

@lisp
(define x (list 'a 'b 'c))
(define y x)
y                           @result{}  (a b c)
(list? y)                   @result{}  #t
(set-cdr! x 4)              @result{}  @emph{unspecified}
x                           @result{}  (a . 4)
(eqv? x y)                  @result{}  #t
y                           @result{}  (a . 4)
(list? y)                   @result{}  #f
(set-cdr! x x)              @result{}  @emph{unspecified}
(list? x)                   @result{}  #f
@end lisp

@c It is often convenient to speak of a homogeneous list of objects
@c of some particular data type, as for example @code{(1 2 3)} is a list of
@c integers.  To be more precise, suppose @var{D} is some data type.  (Any
@c predicate defines a data type consisting of those objects of which the
@c predicate is true.)  Then

@c @itemize @bullet
@c @item The empty list is a list of @var{D}.
@c @item If @var{list} is a list of @var{D}, then any pair whose cdr is
@c       @var{list} and whose car is an element of the data type @var{D} is also a
@c       list of @var{D}.
@c @item There are no other lists of @var{D}.
@c @end itemize

Within literal expressions and representations of objects read by the
@code{read} procedure, the forms @code{'@r{<datum>}},@code{`@r{<datum>}},
@code{,@r{<datum>}}, and @code{,@@@r{<datum>}} denote two-element lists
@findex read
@vindex '
@vindex ,
@vindex ,@@
whose first elements are the symbols @code{quote}, @code{quasiquote},
@code{unquote}, and
@findex quote
@findex quasiquote
@findex unquote
@findex unquote-splicing
@code{unquote-splicing}, respectively.  The second element in each case
is @r{<datum>}.  This convention is supported so that arbitrary Scheme
programs may be represented as lists.
@ignore
todo
Can or need this be stated
more carefully?
@end ignore
That is, according to Scheme's grammar, every
@r{<expression>} is also a @r{<datum>} (see @ref{External representations}).
Among other things, this permits the use of the @code{read} procedure to
@findex read
parse Scheme programs.  See @ref{External representations}.

@deffn {essential procedure} pair? obj

@code{Pair?} returns @code{#t} if @var{obj} is a pair, and otherwise
@findex pair?
returns @code{#f}.

@lisp
(pair? '(a . b))            @result{}  #t
(pair? '(a b c))            @result{}  #t
(pair? '())                 @result{}  #f
(pair? '#(a b))             @result{}  #f
@end lisp
@end deffn

@deffn {essential procedure} cons obj1 obj2

Returns a newly allocated pair whose car is @var{obj1} and whose cdr is
@var{obj2}.  The pair is guaranteed to be different (in the sense of
@code{eqv?}) from every existing object.
@findex eqv?

@lisp
(cons 'a '())               @result{}  (a)
(cons '(a) '(b c d))        @result{}  ((a) b c d)
(cons "a" '(b c))           @result{}  ("a" b c)
(cons 'a 3)                 @result{}  (a . 3)
(cons '(a b) 'c)            @result{}  ((a b) . c)
@end lisp
@end deffn

@deffn {essential procedure} car pair

@c nodomain{@var{Pair} must be a pair.}
Returns the contents of the car field of @var{pair}.  Note that it is an
error to take the car of the empty list.
@cindex empty list

@lisp
(car '(a b c))              @result{}  a
(car '((a) b c d))          @result{}  (a)
(car '(1 . 2))              @result{}  1
(car '())                   @result{}  @emph{error}
@end lisp

@end deffn

@deffn {essential procedure} cdr pair

@c nodomain{@var{Pair} must be a pair.}
Returns the contents of the cdr field of @var{pair}.
Note that it is an error to take the cdr of the empty list.

@lisp
(cdr '((a) b c d))          @result{}  (b c d)
(cdr '(1 . 2))              @result{}  2
(cdr '())                   @result{}  @emph{error}
@end lisp

@end deffn

@deffn {essential procedure} set-car! pair obj

@c nodomain{@var{Pair} must be a pair.}
Stores @var{obj} in the car field of @var{pair}.
The value returned by @code{set-car!} is unspecified.  @c <!>
@findex set-car!
@c This procedure can be very confusing if used indiscriminately.

@lisp
(define (f) (list 'not-a-constant-list))
(define (g) '(constant-list))
(set-car! (f) 3)            @result{}  @emph{unspecified}
(set-car! (g) 3)            @result{}  @emph{error}
@end lisp

@end deffn

@deffn {essential procedure} set-cdr! pair obj

@c nodomain{@var{Pair} must be a pair.}
Stores @var{obj} in the cdr field of @var{pair}.
The value returned by @code{set-cdr!} is unspecified.  @c <!>
@findex set-cdr!
@c This procedure can be very confusing if used indiscriminately.

@end deffn

@c \hbox@code{(cadr @var{pair})}
@c \setbox1\hbox{essential procedure}

@deffn {essential procedure} caar pair
@deffnx {essential procedure} cadr pair
@center @dots{}
@deffnx {essential procedure} cdddar pair
@deffnx {essential procedure} cddddr pair

These procedures are compositions of @code{car} and @code{cdr}, where
@findex cdr
@findex car
for example @code{caddr} could be defined by
@findex caddr

@lisp
(define caddr (lambda (x) (car (cdr (cdr x)))))@r{.}
@end lisp

Arbitrary compositions, up to four deep, are provided.  There are
twenty-eight of these procedures in all.

@end deffn

@deffn {essential procedure} null? obj

Returns @code{#t} if @var{obj} is the empty list, otherwise returns
@code{#f}.
@cindex empty list

@c  @emph{Note:}  @c  In implementations in which the empty
@c  list is the same as @code{#f}, @code{null?} will return @code{#t}
@findex null?
@c  if @var{obj} is @code{#f}.
@c  @c end note

@end deffn

@deffn {essential procedure} list? obj

Returns @code{#t} if @var{obj} is a list, otherwise returns @code{#f}.
By definition, all lists have finite length and are terminated by
the empty list.

@lisp
        (list? '(a b c))    @result{}  #t
        (list? '())         @result{}  #t
        (list? '(a . b))    @result{}  #f
        (let ((x (list 'a)))
          (set-cdr! x x)
          (list? x))        @result{}  #f
@end lisp
@end deffn

@deffn {essential procedure} list obj @dots{}

Returns a newly allocated list of its arguments.

@lisp
(list 'a (+ 3 4) 'c)        @result{}  (a 7 c)
(list)                      @result{}  ()
@end lisp
@end deffn

@deffn {essential procedure} length list

@c nodomain{@var{List} must be a list.}
Returns the length of @var{list}.

@lisp
(length '(a b c))           @result{}  3
(length '(a (b) (c d e)))   @result{}  3
(length '())                @result{}  0
@end lisp
@end deffn

@deffn {essential procedure} append list @dots{}

@c nodomain{All @var{list}s should be lists.}
Returns a list consisting of the elements of the first @var{list}
followed by the elements of the other @var{list}s.

@lisp
(append '(x) '(y))          @result{}  (x y)
(append '(a) '(b c d))      @result{}  (a b c d)
(append '(a (b)) '((c)))    @result{}  (a (b) (c))
@end lisp

The resulting list is always newly allocated, except that it shares
structure with the last @var{list} argument.  The last argument may
actually be any object; an improper list results if the last argument is not a
proper list.
@ignore
todo
This is pretty awkward.  I should get Bartley to fix
this.
@end ignore

@lisp
(append '(a b) '(c . d))    @result{}  (a b c . d)
(append '() 'a)             @result{}  a
@end lisp
@end deffn

@deffn {essential procedure} reverse list

@c nodomain{@var{List} must be a list.}
Returns a newly allocated list consisting of the elements of @var{list}
in reverse order.

@lisp
(reverse '(a b c))          @result{}  (c b a)
(reverse '(a (b c) d (e (f))))  
                            @result{}  ((e (f)) d (b c) a)
@end lisp
@end deffn

@deffn {procedure} list-tail list k

Returns the sublist of @var{list} obtained by omitting the first @var{k}
elements.
@code{List-tail} could be defined by
@findex list-tail

@lisp
(define list-tail
  (lambda (x k)
    (if (zero? k)
        x
        (list-tail (cdr x) (- k 1)))))
@end lisp
@end deffn

@deffn {essential procedure} list-ref list k

Returns the @var{k}th element of @var{list}.  (This is the same
as the car of @code{(list-tail @var{list} @var{k})}.)

@lisp
(list-ref '(a b c d) 2)     @result{}  c
(list-ref '(a b c d)
          (inexact->exact (round 1.8))) 
                            @result{}  c
@end lisp
@end deffn

@c @deffn {procedure} last-pair { list}

@c Returns the last pair in the nonempty, possibly improper, list @var{list}.
@c @code{Last-pair} could be defined by

@c @lisp
@c (define last-pair
@c   (lambda (x)
@c     (if (pair? (cdr x))
@c         (last-pair (cdr x))
@c         x)))
@c @end lisp
@c 
@c @end deffn

@deffn {essential procedure} memq obj list
@deffnx {essential procedure} memv obj list
@deffnx {essential procedure} member obj list

These procedures return the first sublist of @var{list} whose car is
@var{obj}, where the sublists of @var{list} are the non-empty lists
returned by @code{(list-tail @var{list} @var{k})} for @var{k} less
than the length of @var{list}.  If
@var{obj} does not occur in @var{list}, then @code{#f} (not the empty list) is
returned.  @code{Memq} uses @code{eq?} to compare @var{obj} with the
@findex eq?
elements of
@findex memq
@var{list}, while @code{memv} uses @code{eqv?} and @code{member}
@findex member
@findex eqv?
uses @code{equal?}.
@findex equal?
@findex memv

@lisp
(memq 'a '(a b c))          @result{}  (a b c)
(memq 'b '(a b c))          @result{}  (b c)
(memq 'a '(b c d))          @result{}  #f
(memq (list 'a) '(b (a) c)) @result{}  #f
(member (list 'a)
        '(b (a) c))         @result{}  ((a) c)
(memq 101 '(100 101 102))   @result{}  @emph{unspecified}
(memv 101 '(100 101 102))   @result{}  (101 102)
@end lisp

@end deffn

@deffn {essential procedure} assq obj alist
@deffnx {essential procedure} assv obj alist
@deffnx {essential procedure} assoc obj alist

@c domain
@var{Alist} (for ``association list'') must be a list of pairs.  These
procedures find the first pair in @var{alist} whose car field is
@var{obj}, and returns that pair.  If no pair in @var{alist} has
@var{obj} as its car, then @code{#f} (not the empty list) is returned.
@code{Assq} uses @code{eq?} to compare @var{obj} with the car fields of
the pairs in @var{alist}, while @code{assv} uses @code{eqv?} and
@code{assoc} uses @code{equal?}.
@findex assq
@findex assoc
@findex eq?
@findex eqv?
@findex equal?
@findex assv

@lisp
(define e '((a 1) (b 2) (c 3)))
(assq 'a e)                 @result{}  (a 1)
(assq 'b e)                 @result{}  (b 2)
(assq 'd e)                 @result{}  #f
(assq (list 'a) '(((a)) ((b)) ((c))))
                            @result{}  #f
(assoc (list 'a) '(((a)) ((b)) ((c))))
                            @result{}  ((a))
(assq 5 '((2 3) (5 7) (11 13)))
                            @result{}  @emph{unspecified}
(assv 5 '((2 3) (5 7) (11 13)))
                            @result{}  (5 7)
@end lisp

@emph{Rationale:}  Although they are ordinarily used as predicates,
@code{memq}, @code{memv}, @code{member}, @code{assq}, @code{assv}, and
symbols@code{assoc} do not
@findex assq
@findex assv
@findex member
@findex memv
@findex assoc
@findex memq
have question marks in their names because they return useful values
rather than just @code{#t} or @code{#f}.
@c end rationale
@end deffn

@node Symbols, Numbers, Pairs and lists, Standard procedures
@section Symbols
@c label{Symbols}

Symbols are objects whose usefulness rests on the fact that two symbols
are identical (in the sense of @code{eqv?}) if and only if their
@findex eqv?
names are spelled the same way.  This is exactly the property needed to
represent identifiers
@cindex identifier
in programs, and so most implementations of Scheme use them internally
for that purpose.  Symbols are useful for many other applications; for
instance, they may be used the way enumerated values are used in Pascal.

@c vest
The rules for writing a symbol are exactly the same as the rules for
writing an identifier; see @ref{Identifiers}
and @ref{Lexical structure}.

@c vest
It is guaranteed that any symbol that has been returned as part of
a literal expression, or read using the @code{read} procedure, and
@findex read
subsequently written out using the @code{write} procedure, will read
back
@findex write
in as the identical symbol (in the sense of @code{eqv?}).  The
@findex eqv?
@code{string->symbol} procedure, however, can create symbols for
@findex string->symbol
which this write/read invariance may not hold because their names
contain special characters or letters in the non-standard case.

@emph{Note:}  Some implementations of Scheme have a feature known as ``slashification''
in order to guarantee write/read invariance for all symbols, but
historically the most important use of this feature has been to
compensate for the lack of a string data type.

@c vest
Some implementations also have ``uninterned symbols'', which
defeat write/read invariance even in implementations with slashification,
and also generate exceptions to the rule that two symbols are the same
if and only if their names are spelled the same.
@c end note

@deffn {essential procedure} symbol? obj

Returns @code{#t} if @var{obj} is a symbol, otherwise returns @code{#f}.

@lisp
(symbol? 'foo)              @result{}  #t
(symbol? (car '(a b)))      @result{}  #t
(symbol? "bar")             @result{}  #f
(symbol? 'nil)              @result{}  #t
(symbol? '())               @result{}  #f
(symbol? #f)                @result{}  #f
@end lisp
@end deffn

@deffn {essential procedure} symbol->string symbol

Returns the name of @var{symbol} as a string.  If the symbol was part of
an object returned as the value of a literal expression
(@ref{Literal expressions}) or by a call to the @code{read}
@findex read
procedure,
and its name contains alphabetic characters, then the string returned
will contain characters in the implementation's preferred standard
case---some implementations will prefer upper case, others lower case.
If the symbol was returned by @code{string->symbol}, the case of
@findex string->symbol
characters in the string returned will be the same as the case in the
string that was passed to @code{string->symbol}.  It is an error
@findex string->symbol
to apply mutation procedures like @code{string-set!} to strings returned
@findex string-set!
by this procedure.

The following examples assume that the implementation's standard case is
lower case:

@lisp
(symbol->string 'flying-fish)
                            @result{}  "flying-fish"
(symbol->string 'Martin)    @result{}  "martin"
(symbol->string
   (string->symbol "Malvina"))
                            @result{}  "Malvina"
@end lisp
@end deffn

@deffn {essential procedure} string->symbol string

Returns the symbol whose name is @var{string}.  This procedure can
create symbols with names containing special characters or letters in
the non-standard case, but it is usually a bad idea to create such
symbols because in some implementations of Scheme they cannot be read as
themselves.  See @code{symbol->string}.
@findex symbol->string

The following examples assume that the implementation's standard case is
lower case:

@lisp
(eq? 'mISSISSIppi 'mississippi)  
                            @result{}  #t
(string->symbol "mISSISSIppi")  
                            @result{}  @r{the symbol with name} "mISSISSIppi"
(eq? 'bitBlt (string->symbol "bitBlt"))     
                            @result{}  #f
(eq? 'JollyWog
     (string->symbol
       (symbol->string 'JollyWog)))  
                            @result{}  #t
(string=? "K. Harper, M.D."
          (symbol->string
            (string->symbol "K. Harper, M.D.")))  
                            @result{}  #t
@end lisp

@end deffn

@node Numbers, Characters, Symbols, Standard procedures
@section Numbers
@c label{Numbers}

@cindex number

@c %R4%% The excessive use of the code font in this section was
@c  confusing, somewhat obnoxious, and inconsistent with the rest
@c  of the report and with parts of the section itself.  I added
@c  a \tupe no-op, and changed most old uses of \type to \tupe,
@c  to make it easier to change the fonts back if people object
@c  to the change.

@c \newcommand{\type}[1]{{\it#1}}
@c \newcommand{\tupe}[1]{{#1}}

Numerical computation has traditionally been neglected by the Lisp
community.  Until Common Lisp there was no carefully thought out
strategy for organizing numerical computation, and with the exception of
the MacLisp system @sc{[Pitman83]} little effort was made to
execute numerical code efficiently.  This report recognizes the excellent work
of the Common Lisp committee and accepts many of their recommendations.
In some ways this report simplifies and generalizes their proposals in a manner
consistent with the purposes of Scheme.

It is important to distinguish between the mathematical numbers, the
Scheme numbers that attempt to model them, the machine representations
used to implement the Scheme numbers, and notations used to write numbers.
This report uses the types @i{number}, @i{complex}, @i{real},
@i{rational}, and @i{integer} to refer to both mathematical numbers
and Scheme numbers.  Machine representations such as fixed point and
floating point are referred to by names such as @i{fixnum} and
@i{flonum}.

@c %R4%% I did some reorganizing here to move the discussion of mathematical
@c  numbers before the discussion of the Scheme numbers, hoping that this
@c  would help to motivate the discussion of representation independence.

@menu
* Numerical types::
* Exactness::
* Implementation restrictions::
* Syntax of numerical constants::
* Numerical operations::
* Numerical input and output::
@end menu

@node Numerical types, Exactness, Numbers, Numbers
@subsection Numerical types
@c label{Numerical types}

@cindex numerical types

@c %R4%% A Scheme system provides data of type @i{number}, which is the most
@c general numerical type supported by that system.
@c @i{Number} is
@c likely to be a complicated union type implemented in terms of
@c @i{fixnum}s, @i{bignum}s, @i{flonum}s, and so forth, but this
@c should not be apparent to a naive user.  What the user should see is
@c that the usual operations on numbers produce the mathematically
@c expected results, within the limits of the implementation.

@c %R4%%  I rewrote the following paragraph to make the various levels of
@c  the tower into subsets of each other, instead of relating them by
@c  injections.  I think the injections tended to put people in the frame
@c  of mind of thinking about coercions between non-overlapping numeric
@c  types in mainstream programming languages.

@c vest
Mathematically, numbers may be arranged into a tower of subtypes
@c %R4%% with injections relating adjacent levels of the tower:
in which each level is a subset of the level above it:
@itemize @bullet
@item number
@item complex
@item real
@item rational
@item integer
@end itemize

For example, 3 is an integer.  Therefore 3 is also a rational,
a real, and a complex.  The same is true of the Scheme numbers
that model 3.  For Scheme numbers, these types are defined by the
predicates @code{number?}, @code{complex?}, @code{real?},
@code{rational?}, and @code{integer?}.
@findex rational?
@findex real?
@findex complex?
@findex number?
@findex integer?

There is no simple relationship between a number's type and its
representation inside a computer.  Although most implementations of
Scheme will offer at least two different representations of 3, these
different representations denote the same integer.

@c %R4%% I moved "Implementations of Scheme are not required to implement
@c  the whole tower..." to the subsection on implementation restrictions.

Scheme's numerical operations treat numbers as abstract data, as
independent of their representation as possible.  Although an implementation
of Scheme may use fixnum, flonum, and perhaps other representations for
numbers, this should not be apparent to a casual programmer writing
simple programs.

It is necessary, however, to distinguish between numbers that are
represented exactly and those that may not be.  For example, indexes
into data structures must be known exactly, as must some polynomial
coefficients in a symbolic algebra system.  On the other hand, the
results of measurements are inherently inexact, and irrational numbers
may be approximated by rational and therefore inexact approximations.
In order to catch uses of inexact numbers where exact numbers are
required, Scheme explicitly distinguishes exact from inexact numbers.
This distinction is orthogonal to the dimension of type.

@node Exactness, Implementation restrictions, Numerical types, Numbers
@subsection Exactness

@c %R4%% I tried to direct the following paragraph away from philosophizing
@c  about the exactness of mathematical numbers, and toward philosophizing
@c  about the exactness of Scheme numbers.

@cindex @w{exactness}
@c label{Exactness}

Scheme numbers are either @i{exact} or @i{inexact}.  A number is
@r{exact} if it was written as an exact constant or was derived from
@r{exact} numbers using only @r{exact} operations.  A number is
@r{inexact} if it was written as an inexact constant,
@c %R4%% models a quantity (e.g., a measurement) known only approximately,
if it was
derived using @r{inexact} ingredients, or if it was derived using
@r{inexact} operations. Thus @r{inexact}ness is a contagious
property of a number.
@c %R4%% The rest of this paragraph (from R3RS) has been dropped.

@c vest
If two implementations produce @r{exact} results for a
computation that did not involve @r{inexact} intermediate results,
the two ultimate results will be mathematically equivalent.  This is
generally not true of computations involving @r{inexact} numbers
since approximate methods such as floating point arithmetic may be used,
but it is the duty of each implementation to make the result as close as
practical to the mathematically ideal result.

@c vest
Rational operations such as @code{+} should always produce
@findex +
@r{exact} results when given @r{exact} arguments.
@c %R4%%If an implementation is
@c unable to represent an @r{exact} result (for example, if it does not
@c support infinite precision integers and rationals)
If the operation is unable to produce an @r{exact} result,
then it may either report the violation of an implementation restriction
or it may silently coerce its
result to an @r{inexact} value.
@c %R4%%Such a coercion may cause an error later.
See @ref{Implementation restrictions}.

@c vest
With the exception of @code{inexact->exact}, the operations described in
@findex inexact->exact
this section must generally return inexact results when given any inexact
arguments.  An operation may, however, return an @r{exact} result if it can
prove that the value of the result is unaffected by the inexactness of its
arguments.  For example, multiplication of any number by an @r{exact} zero
may produce an @r{exact} zero result, even if the other argument is
@r{inexact}.

@node Implementation restrictions, Syntax of numerical constants, Exactness, Numbers
@subsection Implementation restrictions

@cindex implementation restriction
@c label{Implementation restrictions}

@c vest
Implementations of Scheme are not required to implement the whole
tower of subtypes given in @ref{Numerical types},
but they must implement a coherent subset consistent with both the
purposes of the implementation and the spirit of the Scheme language.
For example, an implementation in which all numbers are @r{real}
may still be quite useful.

@c vest
Implementations may also support only a limited range of numbers of
any type, subject to the requirements of this section.  The supported
range for @r{exact} numbers of any type may be different from the
supported range for @r{inexact} numbers of that type.  For example,
an implementation that uses flonums to represent all its
@r{inexact} @r{real} numbers may
support a practically unbounded range of @r{exact} @r{integer}s
and @r{rational}s
while limiting the range of @r{inexact} @r{real}s (and therefore
the range of @r{inexact} @r{integer}s and @r{rational}s)
to the dynamic range of the flonum format.
Furthermore
the gaps between the representable @r{inexact} @r{integer}s and
@r{rational}s are
likely to be very large in such an implementation as the limits of this
range are approached.

@c vest
An implementation of Scheme must support exact integers
throughout the range of numbers that may be used for indexes of
lists, vectors, and strings or that may result from computing the length of a
list, vector, or string.  The @code{length}, @code{vector-length},
@findex vector-length
@findex length
and @code{string-length} procedures must return an exact
@findex string-length
integer, and it is an error to use anything but an exact integer as an
index.  Furthermore any integer constant within the index range, if
expressed by an exact integer syntax, will indeed be read as an exact
integer, regardless of any implementation restrictions that may apply
outside this range.  Finally, the procedures listed below will always
return an exact integer result provided all their arguments are exact integers
and the mathematically expected result is representable as an exact integer
within the implementation:

@lisp
+            -             *
quotient     remainder     modulo
max          min           abs
numerator    denominator   gcd
lcm          floor         ceiling
truncate     round         rationalize
expt
@end lisp

@c vest
Implementations are encouraged, but not required, to support
@r{exact} @r{integer}s and @r{exact} @r{rational}s of
practically unlimited size and precision, and to implement the
above procedures and the @code{/} procedure in
@findex /
such a way that they always return @r{exact} results when given @r{exact}
arguments.  If one of these procedures is unable to deliver an @r{exact}
result when given @r{exact} arguments, then it may either report a
violation of an
implementation restriction or it may silently coerce its result to an
@r{inexact} number.  Such a coercion may cause an error later.

@c %R4%% I moved this stuff here.
@c  It seems to me that the only thing that this requires is that
@c  implementations that support inexact numbers have to have both
@c  exact and inexact representations for the integers 0 through 15.
@c  If that's what it's saying, I'd rather say it that way.
@c  On the other hand, letting the limit be as small as 15 sounds a
@c  tad silly, though I think I understand how that number was arrived at.
@c  (Or is 35 the number?)

@c Implementations are encouraged, but not required, to support @r{inexact}
@c numbers.  For any implementation that supports @r{inexact} numbers,
@c there is a subset of the integers for which there are both @r{exact} and
@c @r{inexact} representations.  This subset must include all non-negative
@c integers up to some limit specified by the implementation.  This limit
@c must be 16 or greater.  The
@c @code{exact->inexact} and @code{inexact->exact}
@findex inexact->exact
@findex exact->inexact
@c procedures implement the natural one-to-one correspondence between
@c the @r{inexact} and @r{exact} integers within this range.

@c vest
An implementation may use floating point and other approximate
representation strategies for @r{inexact} numbers.
@c %R4%% The following sentence seemed a bit condescending as well as
@c  awkward.  It didn't seem to be very enforceable, so I flushed it.

@c This is not to
@c say that implementors need not use the best known algorithms for
@c @r{inexact} computations---only that approximate methods of high
@c quality are allowed.

This report recommends, but does not require, that the IEEE 32-bit
and 64-bit floating point standards be followed by implementations that use
flonum representations, and that implementations using
other representations should match or exceed the precision achievable
using these floating point standards @sc{[IEEE]}.

@c vest
In particular, implementations that use flonum representations
must follow these rules: A @r{flonum} result
must be represented with at least as much precision as is used to express any of
the inexact arguments to that operation.  It is desirable (but not required) for
potentially inexact operations such as @code{sqrt}, when applied to
@r{exact}
@findex sqrt
arguments, to produce @r{exact} answers whenever possible (for example the
square root of an @r{exact} 4 ought to be an @r{exact} 2).
If, however, an
@r{exact} number is operated upon so as to produce an @r{inexact} result
(as by @code{sqrt}), and if the result is represented as a
@r{flonum}, then
@findex sqrt
the most precise @r{flonum} format available must be used; but if the result
is represented in some other way then the representation must have at least as
much precision as the most precise @r{flonum} format available.

Although Scheme allows a variety of written
@c %R4%% representations of
notations for
numbers, any particular implementation may support only some of them.
@c %R4%
For example, an implementation in which all numbers are @r{real}
need not support the rectangular and polar notations for complex
numbers.  If an implementation encounters an @r{exact} numerical constant that
it cannot represent as an @r{exact} number, then it may either report a
violation of an implementation restriction or it may silently represent the
constant by an @r{inexact} number.

@node Syntax of numerical constants, Numerical operations, Implementation restrictions, Numbers
@subsection Syntax of numerical constants
@c label{Syntax of numerical constants}

@c @@@@LOSE@@@@

@c %R4%%  I removed the following paragraph in an attempt to tighten up
@c  this subsection.  Except for its first sentence, which I moved to
@c  the subsection on implementation restrictions, I think its content
@c  is implied by the rest of the section.

@c Although Scheme allows a variety of written representations of numbers,
@c any particular implementation may support only some of them.
@c These syntaxes are intended to be purely notational; any kind of number
@c may be written in any form that the user deems convenient.  Of course,
@c writing 1/7 as a limited-precision decimal fraction will not express the
@c number exactly, but this approximate form of expression may be just what
@c the user wants to see.

The syntax of the written representations for numbers is described formally in
@ref{Lexical structure}.
@c %R4%%  See @ref{numberformats} for many examples.

A number may be written in binary, octal, decimal, or
hexadecimal by the use of a radix prefix.  The radix prefixes are
@code{#b} (binary),
@vindex #b
@code{#o} (octal),
@vindex #o
@code{#d} (decimal), and
@vindex #d
@code{#x} (hexadecimal).
@vindex #x
With no radix prefix, a number is assumed to be expressed in decimal.

A
@c %R4%
@c  simple
numerical constant may be specified to be either @r{exact} or
@r{inexact} by a prefix.  The prefixes are @code{#e}
@vindex #e
for @r{exact}, and @code{#i}
@vindex #i
for @r{inexact}.  An exactness
prefix may appear before or after any radix prefix that is used.  If
the written representation of a number has no exactness prefix, the
constant may be either @r{inexact} or @r{exact}.  It is
@r{inexact} if it contains a decimal point, an
exponent, or a ``#'' character in the place of a digit,
otherwise it is @r{exact}.
@c %R4%%  With our new syntax, the following sentence is redundant:

@c The written representation of a
@c compound number, such as a ratio or a complex, is exact if and only if
@c all of its constituents are exact.

In systems with @r{inexact} numbers
of varying precisions it may be useful to specify
the precision of a constant.  For this purpose, numerical constants
may be written with an exponent marker that indicates the
desired precision of the @r{inexact}
representation.  The letters @code{s}, @code{f},
@findex f
@findex s
@code{d}, and @code{l} specify the use of @var{short}, @var{single},
@findex l
@findex d
@var{double}, and @var{long} precision, respectively.  (When fewer
than four internal
@c %R4%%@r{flonum}
@r{inexact}
representations exist, the four size
specifications are mapped onto those available.  For example, an
implementation with two internal representations may map short and
single together and long and double together.)  In addition, the
exponent marker @code{e} specifies the default precision for the
@findex e
implementation.  The default precision has at least as much precision
as @var{double}, but
implementations may wish to allow this default to be set by the user.

@lisp
3.14159265358979F0
       @r{ Round to single ---} 3.141593
0.6L0
       @r{ Extend to long ---} .600000000000000
@end lisp

@node Numerical operations, Numerical input and output, Syntax of numerical constants, Numbers
@subsection Numerical operations

The reader is referred to @ref{Entry format} for a summary
of the naming conventions used to specify restrictions on the types of
arguments to numerical routines.
@c %R4%% The following sentence has already been said twice, and the
@c  term "exactness-preserving" is no longer defined by the Report.

@c   Remember that
@c an exactness-preserving operation may coerce its result to inexact if the
@c implementation is unable to represent it exactly.
The examples used in this section assume that any numerical constant written
using an @r{exact} notation is indeed represented as an @r{exact}
number.  Some examples also assume that certain numerical constants written
using an @r{inexact} notation can be represented without loss of
accuracy; the @r{inexact} constants were chosen so that this is
likely to be true in implementations that use flonums to represent
inexact numbers.

@ignore
todo
Scheme provides the usual set of operations for manipulating
numbers, etc.
@end ignore

@deffn {essential procedure} number? obj
@deffnx {essential procedure} complex? obj
@deffnx {essential procedure} real? obj
@deffnx {essential procedure} rational? obj
@deffnx {essential procedure} integer? obj

These numerical type predicates can be applied to any kind of
argument, including non-numbers.  They return @code{#t} if the object is
of the named type, and otherwise they return @code{#f}.
In general, if a type predicate is true of a number then all higher
type predicates are also true of that number.  Consequently, if a type
predicate is false of a number, then all lower type predicates are
also false of that number.
@c %R4%% The new section on implementation restrictions subsumes:
@c  Not every system
@c supports all of these types; for example, it is entirely possible to have a
@c Scheme system that has only @r{integer}s.  Nonetheless every implementation
@c of Scheme must have all of these predicates.

If @var{z} is an inexact complex number, then @code{(real? @var{z})} is true if
and only if @code{(zero? (imag-part @var{z}))} is true.  If @var{x} is an inexact
real number, then @code{(integer? @var{x})} is true if and only if
@code{(= @var{x} (round @var{x}))}.

@lisp
(complex? 3+4i)             @result{}  #t
(complex? 3)                @result{}  #t
(real? 3)                   @result{}  #t
(real? -2.5+0.0i)           @result{}  #t
(real? #e1e10)              @result{}  #t
(rational? 6/10)            @result{}  #t
(rational? 6/3)             @result{}  #t
(integer? 3+0i)             @result{}  #t
(integer? 3.0)              @result{}  #t
(integer? 8/4)              @result{}  #t
@end lisp

@emph{Note:}  The behavior of these type predicates on @r{inexact} numbers
is unreliable, since any inaccuracy may affect the result.
@c end note

@emph{Note:}  In many implementations the @code{rational?} procedure will be the same
@findex rational?
as @code{real?}, and the @code{complex?} procedure will be the same
@findex complex?
as
@findex real?
@code{number?}, but unusual implementations may be able to represent
@findex number?
some irrational numbers exactly or may extend the number system to
support some kind of non-complex numbers.
@c end note

@end deffn

@deffn {essential procedure} exact? z
@deffnx {essential procedure} inexact? z

These numerical predicates provide tests for the exactness of a
quantity.  For any Scheme number, precisely one of these predicates
is true.

@end deffn

@deffn {essential procedure} = z1 z2 z3 @dots{}
@deffnx {essential procedure} < x1 x2 x3 @dots{}
@deffnx {essential procedure} > x1 x2 x3 @dots{}
@deffnx {essential procedure} <= x1 x2 x3 @dots{}
@deffnx {essential procedure} >= x1 x2 x3 @dots{}

@c - Some implementations allow these procedures to take many arguments, to
@c - facilitate range checks.
These procedures return @code{#t} if their arguments are (respectively):
equal, monotonically increasing, monotonically decreasing,
monotonically nondecreasing, or monotonically nonincreasing.

These predicates are required to be transitive.

@emph{Note:}  The traditional implementations of these predicates in Lisp-like
languages are not transitive.
@c end note

@emph{Note:}  While it is not an error to compare @r{inexact} numbers using these
predicates, the results may be unreliable because a small inaccuracy
may affect the result; this is especially true of @code{=} and @code{zero?}.
@findex =
@findex zero?
When in doubt, consult a numerical analyst.
@c end note

@end deffn

@deffn {essential procedure} zero? z
@deffnx {essential procedure} positive? x
@deffnx {essential procedure} negative? x
@deffnx {essential procedure} odd? n
@deffnx {essential procedure} even? n

These numerical predicates test a number for a particular property,
returning @code{#t} or @code{#f}.  See note above.

@end deffn

@deffn {essential procedure} max x1 x2 @dots{}
@deffnx {essential procedure} min x1 x2 @dots{}

These procedures return the maximum or minimum of their arguments.

@lisp
(max 3 4)                   @result{}  4    ; exact
(max 3.9 4)                 @result{}  4.0  ; inexact
@end lisp

@emph{Note:}  If any argument is inexact, then the result will also be inexact (unless
the procedure can prove that the inaccuracy is not large enough to affect the
result, which is possible only in unusual implementations).  If
@code{min} or
@findex min
@code{max} is used to compare numbers of mixed exactness, and the
numerical
@findex max
value of the result cannot be represented as an inexact number without loss of
accuracy, then the procedure may report a violation of an implementation
restriction.
@c end note
@end deffn

@deffn {essential procedure} + z1 @dots{}
@deffnx {essential procedure} * z1 @dots{}

These procedures return the sum or product of their arguments.
@c - These procedures are exactness preserving.

@lisp
(+ 3 4)                     @result{}  7
(+ 3)                       @result{}  3
(+)                         @result{}  0
(* 4)                       @result{}  4
(*)                         @result{}  1
@end lisp

@end deffn

@deffn {essential procedure} - z1 z2
@deffnx {essential procedure} - z
@deffnx {procedure} - z1 z2 @dots{}
@deffnx {essential procedure} / z1 z2
@deffnx {essential procedure} / z
@deffnx {procedure} / z1 z2 @dots{}

With two or more arguments, these procedures return the difference or
quotient of their arguments, associating to the left.  With one argument,
however, they return the additive or multiplicative inverse of their argument.
@c - These procedures are exactness preserving, except that division may
@c - coerce its result to inexact in implementations that do not support
@c - @r{ratnum}s.

@lisp
(- 3 4)                     @result{}  -1
(- 3 4 5)                   @result{}  -6
(- 3)                       @result{}  -3
(/ 3 4 5)                   @result{}  3/20
(/ 3)                       @result{}  1/3
@end lisp

@end deffn

@deffn {essential procedure} abs x

@code{Abs} returns the magnitude of its argument.
@findex abs
@c - @code{Abs} is exactness preserving when its argument is real.
@findex abs
@lisp
(abs -7)                    @result{}  7
@end lisp
@end deffn

@deffn {essential procedure} quotient n1 n2
@deffnx {essential procedure} remainder n1 n2
@deffnx {essential procedure} modulo n1 n2

These
@c - exactness-preserving
procedures implement number-theoretic (integer)
division: For positive integers @var{n1} and @var{n2}, if @var{n3} and
@var{n4} are integers such that 
@table @asis
@item @code{(= n1 (+ (* n2 n3) n4))},
@item @code{(<= 0 n4)}, and
@item @code{(< n4 n2)}.
@end table
Then
@lisp
(quotient @var{n1} @var{n2})            @result{}  @var{n3}
(remainder @var{n1} @var{n2})           @result{}  @var{n4}
(modulo @var{n1} @var{n2})              @result{}  @var{n4}
@end lisp

For integers @var{n1} and @var{n2} with @var{n2} not equal to 0,

@lisp
(= @var{n1} (+ (* @var{n2} (quotient @var{n1} @var{n2}))
               (remainder @var{n1} @var{n2})))
                            @result{}  #t
@end lisp

@noindent
provided all numbers involved in that computation are exact.

The value returned by @code{quotient} always has the sign of the
@findex quotient
product of its arguments.  @code{Remainder} and @code{modulo} differ
@findex modulo
on negative
@findex remainder
arguments---the
@code{remainder} is either zero or has the sign of the dividend,
@findex remainder
while the @code{modulo}
@findex modulo
always has the sign of the divisor:

@lisp
(modulo 13 4)               @result{}  1
(remainder 13 4)            @result{}  1

(modulo -13 4)              @result{}  3
(remainder -13 4)           @result{}  -1

(modulo 13 -4)              @result{}  -3
(remainder 13 -4)           @result{}  1

(modulo -13 -4)             @result{}  -1
(remainder -13 -4)          @result{}  -1

(remainder -13 -4.0)        @result{}  -1.0  ; inexact
@end lisp
@end deffn

@deffn {essential procedure} gcd n1 @dots{}
@deffnx {essential procedure} lcm n1 @dots{}

These procedures return the greatest common divisor or least common
multiple of their arguments.  The result is always non-negative.
@c - These procedures are exactness preserving.

@c %R4%% I added the inexact example.
@lisp
(gcd 32 -36)                @result{}  4
(gcd)                       @result{}  0
(lcm 32 -36)                @result{}  288
(lcm 32.0 -36)              @result{}  288.0  ; inexact
(lcm)                       @result{}  1
@end lisp

@end deffn

@deffn {procedure} numerator q
@deffnx {procedure} denominator q

These procedures return the numerator or denominator of their
argument; the result is computed as if the argument was represented as
a fraction in lowest terms.  The denominator is always positive.  The
denominator of 0 is defined to be 1.
@c - The remarks about denominators are new.
@c - Clearly, they are exactness-preserving procedures.

@ignore
todo
More description and examples needed.
@end ignore

@lisp
(numerator (/ 6 4))         @result{}  3
(denominator (/ 6 4))       @result{}  2
(denominator
  (exact->inexact (/ 6 4))) @result{}  2.0
@end lisp

@end deffn

@deffn {essential procedure} floor x
@deffnx {essential procedure} ceiling x
@deffnx {essential procedure} truncate x
@deffnx {essential procedure} round x

These procedures return integers.
@c vest
@code{Floor} returns the largest integer not larger than @var{x}.
@findex floor
@code{Ceiling} returns the smallest integer not smaller than @var{x}.
@findex ceiling
@code{Truncate} returns the integer closest to @var{x} whose absolute
@findex truncate
value is not larger than the absolute value of @var{x}.  @code{Round}
returns the
@findex round
closest integer to @var{x}, rounding to even when @var{x} is halfway between two
integers.

@emph{Rationale:}  @code{Round} rounds to even for consistency with the default rounding
@findex round
mode specified by the IEEE floating point standard.
@c end rationale

@emph{Note:}  If the argument to one of these procedures is inexact, then the result
will also be inexact.  If an exact value is needed, the
result should be passed to the @code{inexact->exact} procedure.
@findex inexact->exact
@c end note

@lisp
(floor -4.3)                @result{}  -5.0
(ceiling -4.3)              @result{}  -4.0
(truncate -4.3)             @result{}  -4.0
(round -4.3)                @result{}  -4.0

(floor 3.5)                 @result{}  3.0
(ceiling 3.5)               @result{}  4.0
(truncate 3.5)              @result{}  3.0
(round 3.5)                 @result{}  4.0  ; inexact

(round 7/2)                 @result{}  4    ; exact
(round 7)                   @result{}  7
@end lisp

@end deffn

@deffn {procedure} rationalize x y
@c - @deffnx {procedure} rationalize { x}

@code{Rationalize} returns the @emph{simplest} rational number
@findex rationalize
differing from @var{x} by no more than @var{y}.  A rational number
@var{r1} is @emph{simpler} than another rational number @var{r2} if
@cindex @w{simplest rational}
@table @asis
@item @code{(= r1 (/ p1 q1))} and
@item @code{(= r2 (/ p2 q2))} (in lowest terms) and
@item @code{(<= (abs p1) (abs p2))} and
@item @code{(<= (abs q1) (abs q2))}.
@end table
Thus @code{(3/5)} is simpler than @code{(4/7)}.  Although not all
rationals are comparable in this ordering (consider @code{(2/7)} and
@code{(3/5)}) any interval contains a rational number that is simpler
than every other rational number in that interval (the simpler
@code{(2/5)} lies between @code{(2/7)} and @code{(3/5)}).  Note that 0
(@code{0/1}) is the simplest rational of all.

@lisp
@group
(rationalize
  (inexact->exact .3) 1/10)  @result{}  1/3    ; exact
(rationalize .3 1/10)        @result{}  #i1/3  ; inexact
@end group
@end lisp

@end deffn

@deffn {procedure} exp z
@deffnx {procedure} log z
@deffnx {procedure} sin z
@deffnx {procedure} cos z
@deffnx {procedure} tan z
@deffnx {procedure} asin z
@deffnx {procedure} acos z
@deffnx {procedure} atan z
@deffnx {procedure} atan y x

These procedures are part of every implementation that supports
@c %R4%
general
real numbers; they compute the usual transcendental functions.
@code{Log}
@findex log
computes the natural logarithm of @var{z} (not the base ten logarithm).
@code{Asin}, @code{acos}, and @code{atan} compute arcsine
@findex atan
@findex acos
@tex
($\sin^{-1}$)
@end tex
@findex asin
, arccosine
@tex
($\cos^{-1}$)
@end tex
, and arctangent
@tex
($\tan^{-1}$)
@end tex
, respectively.
The two-argument variant of @code{atan} computes @code{(angle
(make-rectangular @var{x} @var{y}))} (see below), even in
implementations that don't support general complex numbers.
@findex atan

In general, the mathematical functions log, arcsine, arccosine, and
arctangent are multiply defined.
For nonzero real @var{x}, the value of
@code{(log x)} is defined to be
the one whose imaginary part lies in the range 
@code{-pi} (exclusive) to @code{pi} (inclusive).  @code{(log 0)} is
undefined.  The value of @code{(log z)} when @var{z} is complex is
defined according to the formula

@tex
@center $\log z = \log {\rm magnitude}(z) + i {\rm angle} (z)$
@end tex

@format
@t{(define (log z) (+ (log (magnitude z)) (* +i (angle z))))}
@end format

With @code{(log)} defined this way, the values of @code{arcsin},
@code{arccos}, and @code{arctan} are according to the following
formulae:

@tex
@center $\sin^{-1} z = -i \log (i z + \sqrt{1 - z^2})$

@center $\cos^{-1} z = \pi / 2 - \sin^{-1} z$

@center $\tan^{-1} z = (\log (1 + i z) - \log (1 - i z)) / (2 i)$
@end tex

@format
@t{(define (asin z) (* -i (log (+ (* +i z) (sqrt (- 1 (* z z)))))))}

@t{(define (acos z) (- (/ pi 2) (asin z)))}

@t{(define (atan z) (/ (log (/ (+ 1 (* +i z)) (- 1 (* +i z)))) (* +i 2))}
@end format

The above specification follows @sc{[CLtL]}, which in turn
cites @sc{[Penfield81]}; refer to these sources for more detailed
discussion of branch cuts, boundary conditions, and implementation of
these functions.  When it is possible these procedures produce a real
result from a real argument.
@c %R4%
@ignore
todo
The cited references are likely to change their branch cuts
soon to allow for the possibility of distinct positive and negative
zeroes, as in IEEE floating point.  We may not want to follow those
changes, since we may want a complex number with zero imaginary part
(whether positive or negative zero) to be treated as a real.  I don't
think there are any better standards for complex arithmetic than the
ones cited, so we're really on our own here.
@end ignore
@end deffn

@deffn {procedure} sqrt z

Returns the principal square root of @var{z}.  The result will have
either positive real part, or zero real part and non-negative imaginary
part.
@end deffn

@deffn {procedure} expt z1 z2

Returns @var{z1} raised to the power @var{z2}:

@example
@center (define (expt z1 z2) (exp z2 (log z1)))
@end example

@code{(expt 0 0)} is defined to be equal to 1.
@end deffn

@c - @deffn {procedure} approximate { z x}
@c -
@c - Returns an approximation to @var{z} in a representation whose precision is
@c - the same as that
@c - of the representation of @var{x}, which must be an inexact number.  The
@c - result is always inexact.
@c -
@c - @lisp
@c - (approximate 3.1415926535 1F10)
@c -                            @result{}  3.14159F0
@c - (approximate 3.1415926535 #I65535)
@c -                            @result{}  #I3
@c - (approximate 3.14F0 1L8)
@c -                            @result{}  3.14L0
@c - (approximate 3.1415926535F0 1L8)
@c -                            @result{}  3.14159L0
@c - @end lisp
@c - @end deffn

@deffn {procedure} make-rectangular x1 x2
@deffnx {procedure} make-polar x3 x4
@deffnx {procedure} real-part z
@deffnx {procedure} imag-part z
@deffnx {procedure} magnitude z
@deffnx {procedure} angle z

These procedures are part of every implementation that supports
@c %R4%
general complex numbers.  Suppose @var{x1}, @var{x2}, @var{x3}, and
@var{x4} are real numbers and @var{z} is a complex number such that

@center @code{(= z (+ x1 (* +i x2) (* x3 (exp (* +i x4)))))}

Then @code{make-rectangular} and @code{make-polar} return @var{z},
@findex make-polar
@findex make-rectangular
@code{real-part} returns @var{x1}, @code{imag-part} returns @var{x2},
@findex imag-part
@findex real-part
@code{magnitude} returns @var{x3}, and @code{angle} returns @var{x4}.
@findex angle
@findex magnitude
In the case of @code{angle}, whose value is not uniquely determined by
the preceding rule, the value returned will be the one in the range
@code{-pi} (exclusive) to @code{pi} (inclusive).

@emph{Rationale:}  @code{Magnitude} is the same as @code{abs} for a real argument,
@findex abs
@findex magnitude
but @code{abs} must be present in all implementations, whereas
@findex abs
@code{magnitude} need only be present in implementations that support
@findex magnitude
general complex numbers.
@c end rationale

@end deffn

@deffn {procedure} exact->inexact z
@deffnx {procedure} inexact->exact z

@code{Exact->inexact} returns an @r{inexact} representation of
@var{z}.
@findex exact->inexact
The value returned is the
@r{inexact} number that is numerically closest to the argument.
@c %R4%%For
@c @r{exact} arguments which have no reasonably close @r{inexact} equivalent,
@c it is permissible to signal an error.
If an @r{exact} argument has no reasonably close @r{inexact} equivalent,
then a violation of an implementation restriction may be reported.

@code{Inexact->exact} returns an @r{exact} representation of
@findex inexact->exact
@var{z}.  The value returned is the @r{exact} number that is numerically
closest to the argument.
@c %R4%%  For @r{inexact} arguments which have no
@c reasonably close @r{exact} equivalent, it is permissible to signal
@c an error.
If an @r{inexact} argument has no reasonably close @r{exact} equivalent,
then a violation of an implementation restriction may be reported.

@c %R%% I moved this to the section on implementation restrictions.
@c For any implementation that supports @r{inexact} quantities,
@c there is a subset of the integers for which there are both @r{exact} and
@c @r{inexact} representations.  This subset must include the non-negative
@c integers up to a limit specified by the implementation.  The limit
@c must be big enough to represent all digits in reasonable radices, and
@c may correspond to some natural word size for the implementation.  For
@c such integers, these procedures implement the natural one-to-one
@c correspondence between the representations.

These procedures implement the natural one-to-one correspondence between
@r{exact} and @r{inexact} integers throughout an
implementation-dependent range.  See @ref{Implementation restrictions}.
@end deffn
@c medskip

@node Numerical input and output,  , Numerical operations, Numbers
@subsection Numerical input and output

@deffn {essential procedure} number->string number
@deffnx {essential procedure} number->string number radix

@var{Radix} must be an exact integer, either 2, 8, 10, or 16.  If omitted,
@var{radix} defaults to 10.
The procedure @code{number->string} takes a
@findex number->string
number and a radix and returns as a string an external representation of
the given number in the given radix such that
@lisp
(let ((number @var{number})
      (radix @var{radix}))
  (eqv? number
        (string->number (number->string number
                                        radix)
                        radix)))
@end lisp
is true.  It is an error if no possible result makes this expression true.

If @var{number} is inexact, the radix is 10, and the above expression
can be satisfied by a result that contains a decimal point,
then the result contains a decimal point and is expressed using the
minimum number of digits (exclusive of exponent and trailing
zeroes) needed to make the above expression
true @sc{[howtoprint]}, @sc{[howtoread]};
otherwise the format of the result is unspecified.

The result returned by @code{number->string}
@findex number->string
never contains an explicit radix prefix.

@emph{Note:}  The error case can occur only when @var{number} is not a complex number
or is a complex number with a non-rational real or imaginary part.
@c end note

@emph{Rationale:}  If @var{number} is an inexact number represented using flonums, and
the radix is 10, then the above expression is normally satisfied by
a result containing a decimal point.  The unspecified case
allows for infinities, NaNs, and non-flonum representations.
@c end rationale

@end deffn

@deffn {essential procedure} string->number string
@deffnx {essential procedure} string->number string radix

@c %R4%% I didn't include the (string->number string radix exactness)
@c  case, since I haven't heard any resolution of the coding to be used
@c  for the third argument.

Returns a number of the maximally precise representation expressed by the
given @var{string}.  @var{Radix} must be an exact integer, either 2, 8, 10,
or 16.  If supplied, @var{radix} is a default radix that may be overridden
by an explicit radix prefix in @var{string} (e.g. @code{"#o177"}).  If @var{radix}
is not supplied, then the default radix is 10.  If @var{string} is not
a syntactically valid notation for a number, then @code{string->number}
@findex string->number
returns @code{#f}.

@lisp
(string->number "100")      @result{}  100
(string->number "100" 16)   @result{}  256
(string->number "1e2")      @result{}  100.0
(string->number "15##")     @result{}  1500.0
@end lisp

@emph{Note:}  Although @code{string->number} is an essential procedure,
@findex string->number
an implementation may restrict its domain in the
following ways.  @code{String->number} is permitted to return
@findex string->number
@code{#f} whenever @var{string} contains an explicit radix prefix.
If all numbers supported by an implementation are real, then
@code{string->number} is permitted to return @code{#f} whenever
@findex string->number
@var{string} uses the polar or rectangular notations for complex
numbers.  If all numbers are integers, then
@code{string->number} may return @code{#f} whenever
@findex string->number
the fractional notation is used.  If all numbers are exact, then
@code{string->number} may return @code{#f} whenever
@findex string->number
an exponent marker or explicit exactness prefix is used, or if
a @code{#} appears in place of a digit.  If all inexact
numbers are integers, then
@code{string->number} may return @code{#f} whenever
@findex string->number
a decimal point is used.
@c end note

@end deffn

@node Characters, Strings, Numbers, Standard procedures
@section Characters
@c label{Characters}

Characters are objects that represent printed characters such as
letters and digits.
@c There is no requirement that the data type of
@c characters be disjoint from other data types; implementations are
@c encouraged to have a separate character data type, but may choose to
@c represent characters as integers, strings, or some other type.
Characters are written using the notation @t{#\}@r{<character>}
or @t{#\}@r{<character name>}.
For example:

@table @code
@item #\a
lower case letter
@item #\A
upper case letter
@item #\(
left parenthesis
@item #\ 
the space character
@item #\space
the preferred way to write a space
@item #\newline
the newline character
@end table

Case is significant in @t{#\}@r{<character>}, but not in
@t{#\}@r{<character name>}.  If @r{<character>} in
@t{#\}@r{<character>} is alphabetic, then the character
following @r{<character>} must be a delimiter character such as a
space or parenthesis.  This rule resolves the ambiguous case where, for
example, the sequence of characters ``@code{#\space}''
could be taken to be either a representation of the space character or a
representation of the character ``@code{#\s}'' followed
by a representation of the symbol ``@code{pace}.''

@ignore
todo
Fix
@end ignore

Characters written in the @t{#\} notation are self-evaluating.
That is, they do not have to be quoted in programs.
@c The @t{#\}
@c notation is not an essential part of Scheme, however.  Even implementations
@c that support the @t{#\} notation for input do not have to
@c support it for output.

@c vest
Some of the procedures that operate on characters ignore the difference
between upper case and lower case.  The procedures that ignore case have
``@code{-ci}'' (for ``case insensitive'') embedded in their names.

@deffn {essential procedure} char? obj

Returns @code{#t} if @var{obj} is a character, otherwise returns @code{#f}.

@end deffn

@deffn {essential procedure} char=? char1 char2
@deffnx {essential procedure} char<? char1 char2
@deffnx {essential procedure} char>? char1 char2
@deffnx {essential procedure} char<=? char1 char2
@deffnx {essential procedure} char>=? char1 char2

@c label{Characters}
@c nodomain{Both @var{char1} and @var{char2} must be characters.}
These procedures impose a total ordering on the set of characters.  It
is guaranteed that under this ordering:

@itemize @bullet
@item The upper case characters are in order.  For example,
@code{(char<? #\A #\B)} returns @code{#t}.
@item The lower case characters are in order.  For example,
@code{(char<? #\a #\b)} returns @code{#t}.
@item The digits are in order.  For example,
@code{(char<? #\0 #\9)} returns @code{#t}.
@item Either all the digits precede all the upper case letters, or vice versa.
@item Either all the digits precede all the lower case letters, or vice versa.
@end itemize

Some implementations may generalize these procedures to take more than
two arguments, as with the corresponding numerical predicates.

@end deffn

@deffn {essential procedure} char-ci=? char1 char2
@deffnx {essential procedure} char-ci<? char1 char2
@deffnx {essential procedure} char-ci>? char1 char2
@deffnx {essential procedure} char-ci<=? char1 char2
@deffnx {essential procedure} char-ci>=? char1 char2

@c nodomain{Both @var{char1} and @var{char2} must be characters.}
These procedures are similar to @code{char=?} et cetera, but they treat
@findex char=?
upper case and lower case letters as the same.  For example,
@code{(char-ci=? #\A #\a)} returns @code{#t}.
Some implementations may generalize these procedures to take more than
two arguments, as with the corresponding numerical predicates.

@end deffn

@deffn {essential procedure} char-alphabetic? char
@deffnx {essential procedure} char-numeric? char
@deffnx {essential procedure} char-whitespace? char
@deffnx {essential procedure} char-upper-case? letter
@deffnx {essential procedure} char-lower-case? letter

These procedures return @code{#t} if their arguments are alphabetic,
numeric, whitespace, upper case, or lower case characters, respectively,
otherwise they return @code{#f}.  The following remarks, which are specific to
the ASCII character set, are intended only as a guide:  The alphabetic characters
are the 52 upper and lower case letters.  The numeric characters are the
ten decimal digits.  The whitespace characters are space, tab, line
feed, form feed, and carriage return.
@end deffn

@c %R4%%@deffn 
@c @deffnx {essential procedure} char-upper-case? { letter}
@c @deffnx {essential procedure} char-lower-case? { letter}

@c domain@var{Letter} must be an alphabetic character.
@c These procedures return @code{#t} if their arguments are upper case or
@c lower case characters, respectively, otherwise they return @code{#f}.
@c @end deffn

@deffn {essential procedure} char->integer char
@deffnx {essential procedure} integer->char n

Given a character, @code{char->integer} returns an exact integer
@findex char->integer
representation of the character.  Given an exact integer that is the image of
a character under @code{char->integer}, @code{integer->char}
@findex char->integer
@findex integer->char
returns that character.  These procedures implement injective order isomorphisms
between the set of characters under the @code{char<=?}
@findex char<=?
ordering and some subset of the integers under the @code{<=}
@findex <=
ordering.  That is, if
@center @code{(char<=? @var{a} @var{b}) @result{} #t  @r{and}  (<= @var{x} @var{y}) @result{} #t}
and @var{x} and @var{y} are in the domain of
@code{integer->char}, then
@findex integer->char

@lisp
(<= (char->integer @var{a})
    (char->integer @var{b}))       @result{}  #t

(char<=? (integer->char @var{x})
         (integer->char @var{y}))  @result{}  #t
@end lisp

@end deffn

@deffn {essential procedure} char-upcase char
@deffnx {essential procedure} char-downcase char

@c nodomain{@var{Char} must be a character.}
These procedures return a character @var{char2} such that @code{
(char-ci=? @var{char} @var{char2})}.  In addition, if @var{char} is
alphabetic, then the result of @code{char-upcase} is upper case and the
@findex char-upcase
result of @code{char-downcase} is lower case.
@findex char-downcase

@end deffn

@node Strings, Vectors, Characters, Standard procedures
@section Strings
@c label{Strings}

Strings are sequences of characters.
@c In some implementations of Scheme
@c they are immutable; other implementations provide destructive procedures
@c such as @code{string-set!} that alter string objects.
@findex string-set!
@c vest
Strings are written as sequences of characters enclosed within doublequotes
(@code{"}).  A doublequote can be written inside a string only by escaping
it with a backslash (@t{\}), as in

@lisp
"The word \"recursion\" has many meanings."
@end lisp

A backslash can be written inside a string only by escaping it with another
backslash.  Scheme does not specify the effect of a backslash within a
string that is not followed by a doublequote or backslash.

@c vest
A string constant may continue from one line to the next, but
the exact contents of such a string are unspecified.
@c  this is
@c usually a bad idea because
@c the exact effect may vary from one computer
@c system to another.

@c vest
The @emph{length} of a string is the number of characters that it
contains.  This number is a non-negative integer that is fixed when the
string is created.  The @dfn{valid indexes} of a string are the
exact non-negative integers less than the length of the string.  The first
character of a string has index 0, the second has index 1, and so on.

@c vest
In phrases such as ``the characters of @var{string} beginning with
index @var{start} and ending with index @var{end},'' it is understood
that the index @var{start} is inclusive and the index @var{end} is
exclusive.  Thus if @var{start} and @var{end} are the same index, a null
substring is referred to, and if @var{start} is zero and @var{end} is
the length of @var{string}, then the entire string is referred to.

@c vest
Some of the procedures that operate on strings ignore the
difference between upper and lower case.  The versions that ignore case
have ``@code{-ci}'' (for ``case insensitive'') embedded in their
names.

@deffn {essential procedure} string? obj

Returns @code{#t} if @var{obj} is a string, otherwise returns @code{#f}.
@end deffn

@deffn {essential procedure} make-string k
@deffnx {essential procedure} make-string k char

@c domain@var{k} must be a non-negative integer, and @var{char} must be
@c a character.
@code{Make-string} returns a newly allocated string of
@findex make-string
length @var{k}.  If @var{char} is given, then all elements of the string
are initialized to @var{char}, otherwise the contents of the
@var{string} are unspecified.

@end deffn

@deffn {essential procedure} string char @dots{}

Returns a newly allocated string composed of the arguments.

@end deffn

@deffn {essential procedure} string-length string

Returns the number of characters in the given @var{string}.
@end deffn

@deffn {essential procedure} string-ref string k

@c domain
@var{k} must be a valid index of @var{string}.
@code{String-ref} returns character @var{k} of @var{string} using
zero-origin indexing.
@findex string-ref
@end deffn

@deffn {essential procedure} string-set! string k char

@c domain %@var{String} must be a string,
@var{k} must be a valid index of @var{string}%, and @var{char} must be a character
.
@code{String-set!} stores @var{char} in element @var{k} of @var{string}
@findex string-set!
and returns an unspecified value.  @c <!>

@lisp
(define (f) (make-string 3 #\*))
(define (g) "***")
(string-set! (f) 0 #\?)     @result{}  @emph{unspecified}
(string-set! (g) 0 #\?)     @result{}  @emph{error}
(string-set! (symbol->string 'immutable)
             0
             #\?)           @result{}  @emph{error}
@end lisp

@end deffn

@deffn {essential procedure} string=? string1 string2
@deffnx {essential procedure} string-ci=? string1 string2

Returns @code{#t} if the two strings are the same length and contain the same
characters in the same positions, otherwise returns @code{#f}.
@code{String-ci=?} treats
@findex string-ci=?
upper and lower case letters as though they were the same character, but
@code{string=?} treats upper and lower case as distinct characters.
@findex string=?

@end deffn

@deffn {essential procedure} string<? string1 string2
@deffnx {essential procedure} string>? string1 string2
@deffnx {essential procedure} string<=? string1 string2
@deffnx {essential procedure} string>=? string1 string2
@deffnx {essential procedure} string-ci<? string1 string2
@deffnx {essential procedure} string-ci>? string1 string2
@deffnx {essential procedure} string-ci<=? string1 string2
@deffnx {essential procedure} string-ci>=? string1 string2

These procedures are the lexicographic extensions to strings of the
corresponding orderings on characters.  For example, @code{string<?} is
@findex string<?
the lexicographic ordering on strings induced by the ordering
@code{char<?} on characters.  If two strings differ in length but
@findex char<?
are the same up to the length of the shorter string, the shorter string
is considered to be lexicographically less than the longer string.

Implementations may generalize these and the @code{string=?} and
@findex string=?
@code{string-ci=?} procedures to take more than two arguments, as with
@findex string-ci=?
the corresponding numerical predicates.

@end deffn

@deffn {essential procedure} substring string start end

@c domain
@var{String} must be a string, and @var{start} and @var{end}
must be exact integers satisfying

@center @code{(<= 0 @i{start} @i{end} (string-length @i{string})@r{.})}

@code{Substring} returns a newly allocated string formed from the
characters of
@findex substring
@var{string} beginning with index @var{start} (inclusive) and ending with index
@var{end} (exclusive).
@end deffn

@deffn {essential procedure} string-append string @dots{}

Returns a newly allocated string whose characters form the concatenation of the
given strings.

@end deffn

@deffn {essential procedure} string->list string
@deffnx {essential procedure} list->string chars

@code{String->list} returns a newly allocated list of the
@findex string->list
characters that make up the given string.  @code{List->string}
@findex list->string
returns a newly allocated string formed from the characters in the list
@var{chars}. @code{String->list} and @code{list->string} are
@findex list->string
@findex string->list
inverses so far as @code{equal?} is concerned.
@findex equal?
@c Implementations that provide
@c destructive operations on strings should ensure that the result of
@c @code{list->string} is newly allocated.
@c @findex list->string

@end deffn

@deffn {procedure} string-copy string

Returns a newly allocated copy of the given @var{string}.

@end deffn

@deffn {procedure} string-fill! string char

Stores @var{char} in every element of the given @var{string} and returns an
unspecified value.  @c <!>

@end deffn

@node Vectors, Control features, Strings, Standard procedures
@section Vectors
@c label{Vectors}

Vectors are heterogenous structures whose elements are indexed
by integers.  A vector typically occupies less space than a list
of the same length, and the average time required to access a randomly
chosen element is typically less for the vector than for the list.

@c vest
The @emph{length} of a vector is the number of elements that it
contains.  This number is a non-negative integer that is fixed when the
vector is created.  The @emph{valid indexes}
@cindex valid indexes
of a vector are the exact non-negative integers less than the length of
the vector.  The first element in a vector is indexed by zero, and the
last element is indexed by one less than the length of the vector.

Vectors are written using the notation @code{#(@var{obj} @dots{})}.
For example, a vector of length 3 containing the number zero in element
0, the list @code{(2 2 2 2)} in element 1, and the string @code{"Anna"} in
element 2 can be written as following:

@lisp
#(0 (2 2 2 2) "Anna")
@end lisp

Note that this is the external representation of a vector, not an
expression evaluating to a vector.  Like list constants, vector
constants must be quoted:

@lisp
'#(0 (2 2 2 2) "Anna")  
          @result{}  #(0 (2 2 2 2) "Anna")
@end lisp

@ignore
todo
Pitman sez: The visual similarity to lists is bound to be confusing
to some.  Elaborate on the distinction.
@end ignore

@deffn {essential procedure} vector? obj

Returns @code{#t} if @var{obj} is a vector, otherwise returns @code{#f}.
@end deffn

@deffn {essential procedure} make-vector k
@deffnx {procedure} make-vector k fill

Returns a newly allocated vector of @var{k} elements.  If a second
argument is given, then each element is initialized to @var{fill}.
Otherwise the initial contents of each element is unspecified.

@end deffn

@deffn {essential procedure} vector obj @dots{}

Returns a newly allocated vector whose elements contain the given
arguments.  Analogous to @code{list}.
@findex list

@lisp
(vector 'a 'b 'c)           @result{}  #(a b c)
@end lisp
@end deffn

@deffn {essential procedure} vector-length vector

Returns the number of elements in @var{vector}.
@end deffn

@deffn {essential procedure} vector-ref vector k

@c domain
@var{k} must be a valid index of @var{vector}.
@code{Vector-ref} returns the contents of element @var{k} of
@findex vector-ref
@var{vector}.

@lisp
(vector-ref '#(1 1 2 3 5 8 13 21)
            5)  
          @result{}  8
(vector-ref '#(1 1 2 3 5 8 13 21)
            (inexact->exact
              (round (* 2 (acos -1))))) 
          @result{}  13
@end lisp
@end deffn

@deffn {essential procedure} vector-set! vector k obj

@c domain
@var{k} must be a valid index of @var{vector}.
@code{Vector-set!} stores @var{obj} in element @var{k} of @var{vector}.
@findex vector-set!
The value returned by @code{vector-set!} is unspecified.  @c <!>
@findex vector-set!

@lisp
(let ((vec (vector 0 '(2 2 2 2) "Anna")))
  (vector-set! vec 1 '("Sue" "Sue"))
  vec)      
          @result{}  #(0 ("Sue" "Sue") "Anna")

(vector-set! '#(0 1 2) 1 "doe")  
          @result{}  @emph{error}  ; constant vector
@end lisp
@end deffn

@deffn {essential procedure} vector->list vector
@deffnx {essential procedure} list->vector list

@code{Vector->list} returns a newly allocated list of the objects
contained
@findex vector->list
in the elements of @var{vector}.  @code{List->vector} returns a newly
@findex list->vector
created vector initialized to the elements of the list @var{list}.

@lisp
(vector->list '#(dah dah didah))  
          @result{}  (dah dah didah)
(list->vector '(dididit dah))   
          @result{}  #(dididit dah)
@end lisp
@end deffn

@deffn {procedure} vector-fill! vector fill

Stores @var{fill} in every element of @var{vector}.
The value returned by @code{vector-fill!} is unspecified.  @c <!>
@findex vector-fill!

@end deffn

@node Control features, Input and output, Vectors, Standard procedures
@section Control features
@c label{Control features}

@c  Intro flushed; not very a propos any more.
@c  Procedures should be discussed somewhere, however.

This chapter describes various primitive procedures which control the
flow of program execution in special ways.
The @code{procedure?} predicate is also described here.
@findex procedure?

@ignore
todo
@code{Procedure?} doesn't belong in a section with the name
``control features.''  What to do?
@end ignore

@deffn {essential procedure} procedure? obj

Returns @code{#t} if @var{obj} is a procedure, otherwise returns @code{#f}.

@lisp
(procedure? car)            @result{}  #t
(procedure? 'car)           @result{}  #f
(procedure? (lambda (x) (* x x)))
                            @result{}  #t
(procedure? '(lambda (x) (* x x)))
                            @result{}  #f
(call-with-current-continuation procedure?)
                            @result{}  #t
@end lisp

@end deffn

@deffn {essential procedure} apply proc args
@deffnx {procedure} apply proc arg1 @dots{} args

@c domain
@var{Proc} must be a procedure and @var{args} must be a list.
The first (essential) form calls @var{proc} with the elements of
@var{args} as the actual arguments.  The second form is a generalization
of the first that calls @var{proc} with the elements of the list
@code{(append (list @var{arg1} @dots{}) @var{args})} as the actual
arguments.

@lisp
(apply + (list 3 4))        @result{}  7

(define compose
  (lambda (f g)
    (lambda args
      (f (apply g args)))))

((compose sqrt *) 12 75)    @result{}  30
@end lisp
@end deffn

@deffn {essential procedure} map proc list1 list2 @dots{}

@c domain
The @var{list}s must be lists, and @var{proc} must be a
procedure taking as many arguments as there are @i{list}s.  If more
than one @var{list} is given, then they must all be the same length.
@code{Map} applies @var{proc} element-wise to the elements of the
@findex map
@var{list}s and returns a list of the results, in order from left to right.
The dynamic order in which @var{proc} is applied to the elements of the
@var{list}s is unspecified.

@lisp
(map cadr '((a b) (d e) (g h)))   
                            @result{}  (b e h)

(map (lambda (n) (expt n n))
     '(1 2 3 4 5))                
                            @result{}  (1 4 27 256 3125)

(map + '(1 2 3) '(4 5 6))   @result{}  (5 7 9)

(let ((count 0))
  (map (lambda (ignored)
         (set! count (+ count 1))
         count)
       '(a b c)))           @result{}  @emph{unspecified}
@end lisp

@end deffn

@deffn {essential procedure} for-each proc list1 list2 @dots{}

The arguments to @code{for-each} are like the arguments to @code{map}, but
@findex map
@findex for-each
@code{for-each} calls @var{proc} for its side effects rather than for
its values.  Unlike @code{map}, @code{for-each} is guaranteed to call
@var{proc} on the elements of the @var{list}s in order from the first
element to the last, and the value returned by @code{for-each} is
unspecified.

@lisp
(let ((v (make-vector 5)))
  (for-each (lambda (i)
              (vector-set! v i (* i i)))
            '(0 1 2 3 4))
  v)                        @result{}  #(0 1 4 9 16)
@end lisp

@end deffn

@deffn {procedure} force promise

Forces the value of @var{promise} (@pxref{Delayed evaluation,delay}).

@findex delay
@cindex promise
If no value has been computed for the promise, then a value is computed
and returned.  The value of the promise is cached (or ``memoized'') so
that if it is forced a second time, the previously computed value is
returned.
@c  without any recomputation.
@c  [As pointed out by Marc Feeley, the "without any recomputation"
@c  isn't necessarily true. --Will]

@lisp
(force (delay (+ 1 2)))     @result{}  3
(let ((p (delay (+ 1 2))))
  (list (force p) (force p)))
                            @result{}  (3 3)

(define a-stream
  (letrec ((next
            (lambda (n)
              (cons n (delay (next (+ n 1)))))))
    (next 0)))
(define head car)
(define tail
  (lambda (stream) (force (cdr stream))))

(head (tail (tail a-stream)))
                            @result{}  2
@end lisp

@code{Force} and @code{delay} are mainly intended for programs written
@cindex Delayed evaluation
@findex force
in functional style.  The following examples should not be considered to
illustrate good programming style, but they illustrate the property that
only one value is computed for a promise, no matter how many times it is
forced.
@c  the value of a promise is computed at most once.
@c  [As pointed out by Marc Feeley, it may be computed more than once,
@c  but as I observed we can at least insist that only one value be
@c  used! -- Will]

@lisp
(define count 0)
(define p
  (delay (begin (set! count (+ count 1))
                (if (> count x)
                    count
                    (force p)))))
(define x 5)
p                           @result{}  @emph{a promise}
(force p)                   @result{}  6
p                           @result{}  @emph{a promise, still}
(begin (set! x 10)
       (force p))           @result{}  6
@end lisp

Here is a possible implementation of @code{delay} and @code{force}.
@cindex Delayed evaluation
@findex delay
Promises are implemented here as procedures of no arguments,
and @code{force} simply calls its argument:
@findex force

@lisp
(define force
  (lambda (object)
    (object)))
@end lisp

We define the expression

@lisp
(delay @r{<expression>})
@end lisp

@noindent
to have the same meaning as the procedure call

@lisp
(make-promise (lambda () @r{<expression>}))@r{,}
@end lisp

@noindent
where @code{make-promise} is defined as follows:
@findex make-promise

@c  @lisp
@c  (define make-promise
@c    (lambda (proc)
@c      (let ((already-run? #f) (result #f))
@c        (lambda ()
@c          (cond ((not already-run?)
@c                 (set! result (proc))
@c                 (set! already-run? #t)))
@c          result))))
@c  @end lisp

@lisp
(define make-promise
  (lambda (proc)
    (let ((result-ready? #f)
          (result #f))
      (lambda ()
        (if result-ready?
            result
            (let ((x (proc)))
              (if result-ready?
                  result
                  (begin (set! result-ready? #t)
                         (set! result x)
                         result))))))))
@end lisp

@emph{Rationale:}  A promise may refer to its own value, as in the last example above.
Forcing such a promise may cause the promise to be forced a second time
before the value of the first force has been computed.
This complicates the definition of @code{make-promise}.
@findex make-promise
@c end rationale

Various extensions to this semantics of @code{delay} and @code{force}
@findex force
@cindex Delayed evaluation
are supported in some implementations:

@itemize @bullet
@item Calling @code{force} on an object that is not a promise may simply
@findex force
return the object.

@item It may be the case that there is no means by which a promise can be
operationally distinguished from its forced value.  That is, expressions
like the following may evaluate to either @code{#t} or to @code{#f},
depending on the implementation:

@lisp
(eqv? (delay 1) 1)          @result{}  @emph{unspecified}
(pair? (delay (cons 1 2)))  @result{}  @emph{unspecified}
@end lisp

@item Some implementations may implement ``implicit forcing,'' where
the value of a promise is forced by primitive procedures like @code{cdr}
@findex cdr
and @code{+}:
@findex +

@lisp
(+ (delay (* 3 7)) 13)      @result{}  34
@end lisp
@end itemize
@end deffn

@deffn {essential procedure} call-with-current-continuation proc

@c label{Control features}
@c domain
@var{Proc} must be a procedure of one
argument. The procedure @code{call-with-current-continuation} packages
@findex call-with-current-continuation
up the current continuation (see the rationale below) as an ``escape
procedure''
@cindex @w{escape procedure}
and passes it as an argument to
@var{proc}.  The escape procedure is a Scheme procedure of one
argument that, if it is later passed a value, will ignore whatever
continuation is in effect at that later time and will give the value
instead to the continuation that was in effect when the escape procedure
was created.

@c vest
The escape procedure that is passed to @var{proc} has
unlimited extent just like any other procedure in Scheme.  It may be stored
in variables or data structures and may be called as many times as desired.

@c vest
The following examples show only the most common uses of
@code{call-with-current-continuation}.  If all real programs were as
@findex call-with-current-continuation
simple as these examples, there would be no need for a procedure with
the power of @code{call-with-current-continuation}.
@findex call-with-current-continuation

@lisp
(call-with-current-continuation
  (lambda (exit)
    (for-each (lambda (x)
                (if (negative? x)
                    (exit x)))
              '(54 0 37 -3 245 19))
    #t))                    @result{}  -3

(define list-length
  (lambda (obj)
    (call-with-current-continuation
      (lambda (return)
        (letrec ((r
                  (lambda (obj)
                    (cond ((null? obj) 0)
                          ((pair? obj)
                           (+ (r (cdr obj)) 1))
                          (else (return #f))))))
          (r obj))))))

(list-length '(1 2 3 4))    @result{}  4

(list-length '(a b . c))    @result{}  #f
@end lisp

@emph{Rationale:}  
@c vest
A common use of @code{call-with-current-continuation} is for
@findex call-with-current-continuation
structured, non-local exits from loops or procedure bodies, but in fact
@code{call-with-current-continuation} is extremely useful for
implementing a
@findex call-with-current-continuation
wide variety of advanced control structures.

@c vest
Whenever a Scheme expression is evaluated there is a
@dfn{continuation} wanting the result of the expression.  The continuation
represents an entire (default) future for the computation.  If the expression is
evaluated at top level, for example, then the continuation might take the
result, print it on the screen, prompt for the next input, evaluate it, and
so on forever.  Most of the time the continuation includes actions
specified by user code, as in a continuation that will take the result,
multiply it by the value stored in a local variable, add seven, and give
the answer to the top level continuation to be printed.  Normally these
ubiquitous continuations are hidden behind the scenes and programmers don't
think much about them.  On rare occasions, however, a programmer may
need to deal with continuations explicitly.
@code{Call-with-current-continuation} allows Scheme programmers to do
@findex call-with-current-continuation
that by creating a procedure that acts just like the current
continuation.

@c vest
Most programming languages incorporate one or more special-purpose
escape constructs with names like @code{exit}, @code{return}, or
@findex return
even @code{goto}.  In 1965, however, Peter Landin @sc{[Landin65]}
invented a general purpose escape operator called the J-operator.  John
Reynolds @sc{[Reynolds72]} described a simpler but equally powerful
construct in 1972.  The @code{catch} special form described by Sussman
@findex catch
and Steele in the 1975 report on Scheme is exactly the same as
Reynolds's construct, though its name came from a less general construct
in MacLisp.  Several Scheme implementors noticed that the full power of the
@code{catch} construct could be provided by a procedure instead of by a
@findex catch
special syntactic construct, and the name
@code{call-with-current-continuation} was coined in 1982.  This name is
@findex call-with-current-continuation
descriptive, but opinions differ on the merits of such a long name, and
some people use the name @code{call/cc} instead.
@findex call/cc
@c end rationale

@end deffn

@node Input and output,  , Control features, Standard procedures
@section Input and output

@menu
* Ports::
* Input::
* Output::
* System interface::
@end menu

@node Ports, Input, Input and output, Input and output
@subsection Ports
@c label{Ports}

Ports represent input and output devices.  To Scheme, an input port is a
Scheme object that can deliver characters upon command, while an output port
is a Scheme object that can accept characters.
@cindex @w{port}

@ignore
todo
Haase: Mention that there are alternatives to files?
@end ignore

@deffn {essential procedure} call-with-input-file string proc
@deffnx {essential procedure} call-with-output-file string proc

@c domain
@var{Proc} should be a procedure of one argument, and
@var{string} should be a string naming a file.  For
@code{call-with-input-file}, the file must already exist; for
@findex call-with-input-file
@code{call-with-output-file}, the effect is unspecified if the file
@findex call-with-output-file
already exists. These procedures call @var{proc} with one argument: the
port obtained by opening the named file for input or output.  If the
file cannot be opened, an error is signalled.  If the procedure returns,
then the port is closed automatically and the value yielded by the
procedure is returned.  If the procedure does not return, then
the port will not be closed automatically unless it is possible to
prove that the port will never again be used for a read or write
operation.
@c Scheme
@c will not close the port unless it can prove that the port will never
@c again be used for a read or write operation.

@emph{Rationale:}  Because Scheme's escape procedures have unlimited extent, it  is
possible to escape from the current continuation but later to escape back in.
If implementations were permitted to close the port on any escape from the
current continuation, then it would be impossible to write portable code using
both @code{call-with-current-continuation} and
@code{call-with-input-file} or @code{call-with-output-file}.
@findex call-with-current-continuation
@findex call-with-output-file
@findex call-with-input-file
@ignore
todo
Pitman wants more said here; maybe encourage users to call
@code{close-foo-port}; maybe talk about process switches (?).
@end ignore

@c end rationale
@end deffn

@deffn {essential procedure} input-port? obj
@deffnx {essential procedure} output-port? obj

Returns @code{#t} if @var{obj} is an input port or output port
respectively, otherwise returns @code{#f}.

@ignore
todo
Won't necessarily return true after port is closed.
@end ignore

@end deffn

@deffn {essential procedure} current-input-port 
@deffnx {essential procedure} current-output-port 

Returns the current default input or output port.

@end deffn

@deffn {procedure} with-input-from-file string thunk
@deffnx {procedure} with-output-to-file string thunk

@c domain
@var{Thunk} must be a procedure of no arguments, and
@var{string} must be a string naming a file.  For
@code{with-input-from-file}, the file must already exist; for
@findex with-input-from-file
@code{with-output-to-file}, the effect is unspecified if the file
already
@findex with-output-to-file
exists. The file is opened for input or output, an input or output port
connected to it is made the default value returned by
@code{current-input-port} or @code{current-output-port}, and the
@findex current-output-port
@findex current-input-port
@var{thunk} is called with no arguments.  When the @var{thunk} returns,
the port is closed and the previous default is restored.
@code{With-input-from-file} and @code{with-output-to-file} return the
@findex with-output-to-file
@findex with-input-from-file
value yielded by @var{thunk}.
If an escape procedure
is used to escape from the continuation of these procedures, their
behavior is implementation dependent.

@ignore
todo
Kelsey sez he'd hate to try to implement this.
@end ignore

@ignore
todo
OK this with authors??
@end ignore

@c current continuation changes in such a way
@c as to make it doubtful that the @var{thunk} will ever return.

@ignore
todo Freeman: Throughout this section I wanted to see ``the value of
@code{(current-input-port)}'' instead of ``the value returned by
@code{current-input-port}''.  (Same for @code{current-output-port}.)
@end ignore

@end deffn

@deffn {essential procedure} open-input-file filename

Takes a string naming an existing file and returns an input port capable of
delivering characters from the file.  If the file cannot be opened, an error is
signalled.

@end deffn

@deffn {essential procedure} open-output-file filename

Takes a string naming an output file to be created and returns an output
port capable of writing characters to a new file by that name.  If the file
cannot be opened, an error is signalled.  If a file with the given name
already exists, the effect is unspecified.

@end deffn

@deffn {essential procedure} close-input-port port
@deffnx {essential procedure} close-output-port port

Closes the file associated with @var{port}, rendering the @var{port}
incapable of delivering or accepting characters.
@ignore
todo
But maybe a no-op
on some ports, e.g. terminals or editor buffers.
@end ignore

These routines have no effect if the file has already been closed.
The value returned is unspecified.

@ignore
todo
Ramsdell:  Some note is needed explaining why there are two
different close procedures.
@end ignore

@ignore
todo
A port isn't necessarily still a port after it has been
closed?
@end ignore

@end deffn

@node Input, Output, Ports, Input and output
@subsection Input
@c label{Input}

@c \noindent \hbox{ }  %???
@c \vspace{-5ex}
@ignore
todo
The input routines have some things in common, maybe
explain here.
@end ignore

@deffn {essential procedure} read 
@deffnx {essential procedure} read port

@code{Read} converts external representations of Scheme objects into the
@findex read
objects themselves.  That is, it is a parser for the nonterminal
@r{<datum>} (see @ref{External representations} and
@ref{Pairs and lists}).  @code{Read} returns the next
object parsable from the given input @var{port}, updating @var{port} to point to
the first character past the end of the external representation of the object.

@c vest
If an end of file is encountered in the input before any characters are
found that can begin an object, then an end of file object is returned.
The port remains open, and further attempts to read will also return an
end of file object.  If an end of file is encountered after the
beginning of an object's external representation, but the external
representation is incomplete and therefore not parsable, an error is
signalled.

The @var{port} argument may be omitted, in which case it defaults to the
value returned by @code{current-input-port}.  It is an error to read
from a closed port.
@findex current-input-port
@end deffn

@deffn {essential procedure} read-char 
@deffnx {essential procedure} read-char port

Returns the next character available from the input @var{port}, updating
the @var{port} to point to the following character.  If no more characters
are available, an end of file object is returned.  @var{Port} may be
omitted, in which case it defaults to the value returned by
@code{current-input-port}.
@findex current-input-port

@end deffn

@deffn {essential procedure} peek-char 
@deffnx {essential procedure} peek-char port

Returns the next character available from the input @var{port},
@emph{without} updating
the @var{port} to point to the following character.  If no more characters
are available, an end of file object is returned.  @var{Port} may be
omitted, in which case it defaults to the value returned by
@code{current-input-port}.
@findex current-input-port

@emph{Note:}  The value returned by a call to @code{peek-char} is the same as the
@findex peek-char
value that would have been returned by a call to @code{read-char} with
the
@findex read-char
same @var{port}.  The only difference is that the very next call to
@code{read-char} or @code{peek-char} on that @var{port} will return
@findex peek-char
the
@findex read-char
value returned by the preceding call to @code{peek-char}.  In
particular, a call
@findex peek-char
to @code{peek-char} on an interactive port will hang waiting for input
@findex peek-char
whenever a call to @code{read-char} would have hung.
@findex read-char
@c end note

@end deffn

@deffn {essential procedure} eof-object? obj

Returns @code{#t} if @var{obj} is an end of file object, otherwise returns
@code{#f}.  The precise set of end of file objects will vary among
implementations, but in any case no end of file object will ever be an object
that can be read in using @code{read}.
@findex read

@end deffn

@deffn {procedure} char-ready? 
@deffnx {procedure} char-ready? port

Returns @code{#t} if a character is ready on the input @var{port} and
returns @code{#f} otherwise.  If @code{char-ready} returns @code{#t}
then
@findex char-ready
the next @code{read-char} operation on the given @var{port} is
guaranteed
@findex read-char
not to hang.  If the @var{port} is at end of file then
@code{char-ready?} returns @code{#t}.
@findex char-ready?
@var{Port} may be omitted, in which case it defaults to
the value returned by @code{current-input-port}.
@findex current-input-port

@emph{Rationale:}  @code{Char-ready?} exists to make it possible for a program to
@findex char-ready?
accept characters from interactive ports without getting stuck waiting
for input.  Any input editors associated with such ports must ensure
that characters whose existence has been asserted by @code{char-ready?}
@findex char-ready?
cannot be rubbed out.  If @code{char-ready?} were to return @code{#f} at
end of file, a port at end of file would be indistinguishable from an
interactive port that has no ready characters.
@c end rationale
@end deffn

@node Output, System interface, Input, Input and output
@subsection Output
@c label{Output}

@c  We've got to put something here to fix the indentation!!
@c \noindent \hbox{}
@c \vspace{-5ex}

@deffn {essential procedure} write obj
@deffnx {essential procedure} write obj port

Writes a written representation of @var{obj} to the given @var{port}.  Strings
that appear in the written representation are enclosed in doublequotes, and
within those strings backslash and doublequote characters are
escaped by backslashes.  @code{Write} returns an unspecified value.  The
@findex write
@var{port} argument may be omitted, in which case it defaults to the value
returned by @code{current-output-port}.
@findex current-output-port

@end deffn

@deffn {essential procedure} display obj
@deffnx {essential procedure} display obj port

Writes a representation of @var{obj} to the given @var{port}.  Strings
that appear in the written representation are not enclosed in
doublequotes, and no characters are escaped within those strings.  Character
objects appear in the representation as if written by @code{write-char}
@findex write-char
instead of by @code{write}.  @code{Display} returns an unspecified
@findex display
value.
@findex write
The @var{port} argument may be omitted, in which case it defaults to the
value returned by @code{current-output-port}.
@findex current-output-port

@emph{Rationale:}  @code{Write} is intended
@findex write
for producing machine-readable output and @code{display} is for
producing
@findex display
human-readable output.  Implementations that allow ``slashification''
within symbols will probably want @code{write} but not @code{display}
@findex display
to
@findex write
slashify funny characters in symbols.
@c end rationale
@end deffn

@deffn {essential procedure} newline 
@deffnx {essential procedure} newline port

Writes an end of line to @var{port}.  Exactly how this is done differs
from one operating system to another.  Returns an unspecified value.
The @var{port} argument may be omitted, in which case it defaults to the
value returned by @code{current-output-port}.
@findex current-output-port

@end deffn

@deffn {essential procedure} write-char char
@deffnx {essential procedure} write-char char port

Writes the character @var{char} (not an external representation of the
character) to the given @var{port} and returns an unspecified value.  The
@var{port} argument may be omitted, in which case it defaults to the value
returned by @code{current-output-port}.
@findex current-output-port

@end deffn

@node System interface,  , Output, Input and output
@subsection System interface

Questions of system interface generally fall outside of the domain of this
report.  However, the following operations are important enough to
deserve description here.

@deffn {essential procedure} load filename

@ignore
todo
Fix
@end ignore

@c domain
@var{Filename} should be a string naming an existing file
containing Scheme source code. The @code{load} procedure reads
@findex load
expressions and definitions from the file and evaluates them
sequentially.  It is unspecified whether the results of the expressions
are printed.  The @code{load} procedure does not affect the values
@findex load
returned by @code{current-input-port} and @code{current-output-port}.
@findex current-output-port
@findex current-input-port
@code{Load} returns an unspecified value.
@findex load

@emph{Rationale:}  For portability, @code{load} must operate on source files.
@findex load
Its operation on other kinds of files necessarily varies among
implementations.
@c end rationale
@end deffn

@deffn {procedure} transcript-on filename
@deffnx {procedure} transcript-off 

@c domain
@var{Filename} must be a string naming an output file to be
created. The effect of @code{transcript-on} is to open the named file
@findex transcript-on
for output, and to cause a transcript of subsequent interaction between
the user and the Scheme system to be written to the file.  The
transcript is ended by a call to @code{transcript-off}, which closes the
@findex transcript-off
transcript file.  Only one transcript may be in progress at any time,
though some implementations may relax this restriction.  The values
returned by these procedures are unspecified.

@c @emph{Note:}  @c These procedures are redundant in some systems, but
@c systems that need them should provide them.
@c @c end note
@end deffn

@node Formal syntax and semantics, Notes, Standard procedures, Top
@chapter Formal syntax and semantics
@c label{Formal syntax and semantics}

This chapter provides formal descriptions of what has already been
described informally in previous chapters of this report.

@menu
* Formal syntax::
* Formal semantics::
* Derived expression types:Formal derived expression types
@end menu

@ignore
todo
Allow grammar to say that else clause needn't be last?
@end ignore

@node Formal syntax, Formal semantics, Formal syntax and semantics, Formal syntax and semantics
@section Formal syntax
@c label{Formal syntax}

This section provides a formal syntax for Scheme written in an extended
BNF.  The syntax for the entire language, including features which are
not essential, is given here.

All spaces in the grammar are for legibility.  Case is insignificant;
for example, @code{#x1A} and @code{#X1a} are equivalent.  @r{<empty>}
stands for the empty string.

The following extensions to BNF are used to make the description more
concise:  @r{<thing>}@r{*} means zero or more occurrences of
@r{<thing>}; and @r{<thing>}@r{+} means at least one
@r{<thing>}.

@menu
* Lexical structure::
* External representations:External representation
* Expression:Expression syntax
* Quasiquotations::
* Programs and definitions::
@end menu

@node Lexical structure, External representation, Formal syntax, Formal syntax
@subsection Lexical structure

This section describes how individual tokens
@cindex token
(identifiers, numbers, etc.) are formed from sequences of characters.
The following sections describe how expressions and programs are formed
from sequences of tokens.

@r{<Intertoken space>} may occur on either side of any token, but not
within a token.

@c vest
Tokens which require implicit termination (identifiers, numbers,
characters, and dot) may be terminated by any @r{<delimiter>}, but not
necessarily by anything else.

@c grammar
@format
@r{<token>} @expansion{} @r{<identifier>} | @r{<boolean>} | @r{<number>}
@cindex identifier
     | @r{<character>} | @r{<string>}
     | ( | ) | #( | ' | `@{@} | , | ,@ | @b{.}
@r{<delimiter>} @expansion{} @r{<whitespace>} | ( | ) | " | ;
@r{<whitespace>} @expansion{} @r{<space or newline>}
@r{<comment>} @expansion{} ; \= @r{<all subsequent characters up to a line break>}
@cindex comment
@r{<atmosphere>} @expansion{} @r{<whitespace>} | @r{<comment>}
@r{<intertoken space>} @expansion{} @r{<atmosphere>}@r{*}
@end format

@c label{Lexical structure}
@c label{Lexical structure}

@c  This is a kludge, but \multicolumn doesn't work in tabbing environments.
@c \setbox0\hbox@code{@r{<variable>} \goesto{} $\langle$}

@c grammar
@format
@r{<identifier>} @expansion{} @r{<initial>} @r{<subsequent>}@r{*}
     | @r{<peculiar identifier>}
@r{<initial>} @expansion{} @r{<letter>} | @r{<special initial>}
@r{<letter>} @expansion{} a | b | c | ... | z
@r{<special initial>} @expansion{} ! | \$ | \% | \verb"&" | * | / | : | < | =
     | > | ? | \verb" " | \verb"_" | \verb"^"
@r{<subsequent>} @expansion{} @r{<initial>} | @r{<digit>}
     | @r{<special subsequent>}
@r{<digit>} @expansion{} 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
@r{<special subsequent>} @expansion{} .@: | + | -
@r{<peculiar identifier>} @expansion{} + | - | ...
@c | 1+ | -1+
@r{<syntactic keyword>} @expansion{} @r{<expression keyword>}
     | else | => | define
     | unquote | unquote-splicing
@r{<expression keyword>} @expansion{} quote | lambda | if
     | set! | begin | cond | and | or | case
     | let | let* | letrec | do | delay
     | quasiquote
@cindex keyword
@cindex syntactic keyword
@cindex variable
@c \copy0\rm any @r{<identifier>} that isn't
@c \hbox to 1\wd0{\hfill} \rm also a @r{<syntactic keyword>}$\rangle$

@r{<boolean>} @expansion{} @code{#t} | @code{#f}
@r{<character>} @expansion{} @t{#\} @r{<any character>}
     | @t{#\} @r{<character name>}
@r{<character name>} @expansion{} space | newline

@ignore
todo
Explain what happens in the ambiguous case.
@end ignore

@r{<string>} @expansion{} " @r{<string element>}@r{*} "
@r{<string element>} @expansion{} @r{<any character other than @t{"} or @t{\}>}
     | @t{\"} | @t{\\}
@end format

@c label{Lexical structure}

@c grammar
@format
@r{<number>} @expansion{} @r{<num @i{2}>} | @r{<num @i{8}>}
     | @r{<num @i{10}>} | @r{<num @i{16}>}
@end format

The following rules for @r{<num @i{R}>}, @r{<complex @i{R}>}, @r{<real
@i{R}>}, @r{<ureal @i{R}>}, @r{<uinteger @i{R}>}, and @r{<prefix @i{R}>}
should be replicated for @i{R = 2, 8, 10,}
and @i{16}.  There are no rules for @r{<decimal @i{2}>}, @r{<decimal
@i{8}>}, and @r{<decimal @i{16}>}, which means that numbers containing
decimal points or exponents must be in decimal radix.

@ignore
todo
Mark Meyer and David Bartley want to fix this.  (What? --
Will)
@end ignore

@c grammar
@format
@r{<num @i{R}>} @expansion{} @r{<prefix @i{R}>} @r{<complex @i{R}>}
@r{<complex @i{R}>} @expansion{} @r{<real @i{R}>} | @r{<real @i{R}>} @ @r{<real @i{R}>}
     | @r{<real @i{R}>} + @r{<ureal @i{R}>} i | @r{<real @i{R}>} - @r{<ureal @i{R}>} i
     | @r{<real @i{R}>} + i | @r{<real @i{R}>} - i
     | + @r{<ureal @i{R}>} i | - @r{<ureal @i{R}>} i | + i | - i
@r{<real @i{R}>} @expansion{} @r{<sign>} @r{<ureal @i{R}>}
@r{<ureal @i{R}>} @expansion{} @r{<uinteger @i{R}>}
     | @r{<uinteger @i{R}>} / @r{<uinteger @i{R}>}
     | @r{<decimal @i{R}>}
@r{<decimal @i{10}>} @expansion{} @r{<uinteger @i{10}>} @r{<suffix>}
     | . @r{<digit @i{10}>}@r{+} #@r{*} @r{<suffix>}
     | @r{<digit @i{10}>}@r{+} . @r{<digit @i{10}>}@r{*} #@r{*} @r{<suffix>}
     | @r{<digit @i{10}>}@r{+} #@r{+} . #@r{*} @r{<suffix>}
@r{<uinteger @i{R}>} @expansion{} @r{<digit @i{R}>}@r{+} #@r{*}
@r{<prefix @i{R}>} @expansion{} @r{<radix @i{R}>} @r{<exactness>}
     | @r{<exactness>} @r{<radix @i{R}>}
@end format

@c grammar
@format
@r{<suffix>} @expansion{} @r{<empty>}
     | @r{<exponent marker>} @r{<sign>} @r{<digit @i{10}>}@r{+}
@r{<exponent marker>} @expansion{} e | s | f | d | l
@r{<sign>} @expansion{} @r{<empty>}  | + |  -
@r{<exactness>} @expansion{} @r{<empty>} | #i | #e
@vindex #i
@vindex #e
@r{<radix 2>} @expansion{} #b
@vindex #b
@r{<radix 8>} @expansion{} #o
@vindex #o
@r{<radix 10>} @expansion{} @r{<empty>} | #d
@r{<radix 16>} @expansion{} #x
@vindex #x
@r{<digit 2>} @expansion{} 0 | 1
@r{<digit 8>} @expansion{} 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7
@r{<digit 10>} @expansion{} @r{<digit>}
@r{<digit 16>} @expansion{} @r{<digit @i{10}>} | a | b | c | d | e | f
@end format

@ignore
todo
Mark Meyer of TI sez, shouldn't we allow @code{1e3/2}?
@end ignore

@node External representation, Expression syntax, Lexical structure, Formal syntax
@subsection External representation
@c label{External representations}

@r{<Datum>} is what the @code{read} procedure (@ref{Input})
@findex read
successfully parses.  Note that any string that parses as an
@r{<expression>} will also parse as a @r{<datum>}.

@c grammar
@format
@r{<datum>} @expansion{} @r{<simple datum>} | @r{<compound datum>}
@r{<simple datum>} @expansion{} @r{<boolean>} | @r{<number>}
     | @r{<character>} | @r{<string>} |  @r{<symbol>}
@r{<symbol>} @expansion{} @r{<identifier>}
@r{<compound datum>} @expansion{} @r{<list>} | @r{<vector>}
@r{<list>} @expansion{} (@r{<datum>}@r{*}) | (@r{<datum>}@r{+} .@: @r{<datum>})
     | @r{<abbreviation>}
@r{<abbreviation>} @expansion{} @r{<abbrev prefix>} @r{<datum>}
@r{<abbrev prefix>} @expansion{} ' | ` | , | ,@@
@r{<vector>} @expansion{} #(@r{<datum>}@r{*})
@end format

@node Expression syntax, Quasiquotations, External representation, Formal syntax
@subsection Expressions

@c grammar
@format
@r{<expression>} @expansion{} @r{<variable>}
     | @r{<literal>}
     | @r{<procedure call>}
     | @r{<lambda expression>}
     | @r{<conditional>}
     | @r{<assignment>}
     | @r{<derived expression>}

@r{<literal>} @expansion{} @r{<quotation>} | @r{<self-evaluating>}
@r{<self-evaluating>} @expansion{} @r{<boolean>} | @r{<number>}
     | @r{<character>} | @r{<string>}
@r{<quotation>} @expansion{} '@r{<datum>} | (quote @r{<datum>})
@r{<procedure call>} @expansion{} (@r{<operator>} @r{<operand>}@r{*})
@r{<operator>} @expansion{} @r{<expression>}
@r{<operand>} @expansion{} @r{<expression>}

@r{<lambda expression>} @expansion{} (lambda @r{<formals>} @r{<body>})
@r{<formals>} @expansion{} (@r{<variable>}@r{*}) | @r{<variable>}
     | (@r{<variable>}@r{+} .@: @r{<variable>})
@r{<body>} @expansion{} @r{<definition>}@r{*} @r{<sequence>}
@r{<sequence>} @expansion{} @r{<command>}@r{*} @r{<expression>}
@r{<command>} @expansion{} @r{<expression>}

@r{<conditional>} @expansion{} (if @r{<test>} @r{<consequent>} @r{<alternate>})
@r{<test>} @expansion{} @r{<expression>}
@r{<consequent>} @expansion{} @r{<expression>}
@r{<alternate>} @expansion{} @r{<expression>} | @r{<empty>}

@r{<assignment>} @expansion{} (set! @r{<variable>} @r{<expression>})

@r{<derived expression>} @expansion{}
      (cond @r{<cond clause>}@r{+})
     | (cond @r{<cond clause>}@r{*} (else @r{<sequence>}))
     | (case @r{<expression>}
        @r{<case clause>}@r{+})
     | (case @r{<expression>}
        @r{<case clause>}@r{*}
        (else @r{<sequence>}))
     | (and @r{<test>}@r{*})
     | (or @r{<test>}@r{*})
     | (let (@r{<binding spec>}@r{*}) @r{<body>})
     | (let @r{<variable>} (@r{<binding spec>}@r{*}) @r{<body>})
     | (let* (@r{<binding spec>}@r{*}) @r{<body>})
     | (letrec (@r{<binding spec>}@r{*}) @r{<body>})
     | (begin @r{<sequence>})
     | (do (@r{<iteration spec>}@r{*})
          (@r{<test>} @r{<sequence>})
        @r{<command>}@r{*})
     | (delay @r{<expression>})
     | @r{<quasiquotation>}

@r{<cond clause>} @expansion{} (@r{<test>} @r{<sequence>})
     | (@r{<test>})
     | (@r{<test>} => @r{<recipient>})
@r{<recipient>} @expansion{} @r{<expression>}
@r{<case clause>} @expansion{} ((@r{<datum>}@r{*}) @r{<sequence>})

@r{<binding spec>} @expansion{} (@r{<variable>} @r{<expression>})
@r{<iteration spec>} @expansion{} (@r{<variable>} @r{<init>} @r{<step>})
     | (@r{<variable>} @r{<init>})
@r{<init>} @expansion{} @r{<expression>}
@r{<step>} @expansion{} @r{<expression>}
@end format

@node Quasiquotations, Programs and definitions, Expression syntax, Formal syntax
@subsection Quasiquotations

The following grammar for quasiquote expressions is not context-free.
It is presented as a recipe for generating an infinite number of
production rules.  Imagine a copy of the following rules for
@w{@i{D = 1, 2, 3, @dots{}}}.  @i{D} keeps track of the nesting depth.

@c grammar
@format
@r{<quasiquotation>} @expansion{} @r{<quasiquotation 1>}
@r{<template 0>} @expansion{} @r{<expression>}
@r{<quasiquotation @i{D}>} @expansion{} `@r{<template @i{D}>}
     | (quasiquote @r{<template @i{D}>})
@r{<template @i{D}>} @expansion{} @r{<simple datum>}
     | @r{<list template @i{D}>}
     | @r{<vector template @i{D}>}
     | @r{<unquotation @i{D}>}
@r{<list template @i{D}>} @expansion{} (@r{<template or splice @i{D}>}@r{*})
     | (@r{<template or splice @i{D}>}@r{+} .@: @r{<template @i{D}>})
     | '@r{<template @i{D}>}
     | @r{<quasiquotation @i{D+1}>}
@r{<vector template @i{D}>} @expansion{} #(@r{<template or splice @i{D}>}@r{*})
@r{<unquotation @i{D}>} @expansion{} ,@r{<template @i{D-1}>}
     | (unquote @r{<template @i{D-1}>})
@r{<template or splice @i{D}>} @expansion{} @r{<template @i{D}>}
     | @r{<splicing unquotation @i{D}>}
@r{<splicing unquotation @i{D}>} @expansion{} ,@r{<template @i{D-1}>}
     | (unquote-splicing @r{<template @i{D-1}>})
@end format

In @r{<quasiquotation>}s, a @w{@r{<list template @i{D}>}} can sometimes be
confused with either an @w{@r{<unquotation @i{D}>}} or a
@w{@r{<splicing unquotation @i{D}>}}.  The interpretation as an
@r{<unquotation>} or @w{@r{<splicing unquotation @i{D}>}} takes precedence.

@node Programs and definitions,  , Quasiquotations, Formal syntax
@subsection Programs and definitions

@c grammar
@format
@r{<program>} @expansion{} @r{<command or definition>}@r{*}
@r{<command or definition>} @expansion{} @r{<command>} | @r{<definition>}
@r{<definition>} @expansion{} (define @r{<variable>} @r{<expression>})
     | (define (@r{<variable>} @r{<def formals>}) @r{<body>})
     | (begin @r{<definition>}@r{*})
@r{<def formals>} @expansion{} @r{<variable>}@r{*}
     | @r{<variable>}@r{+} .@: @r{<variable>}
@end format

@c @page
@node Formal semantics, Formal derived expression types, Formal syntax, Formal syntax and semantics
@section Formal semantics
@c label{Formal semantics}

This section provides a formal denotational semantics for the primitive
expressions of Scheme and selected built-in procedures.  The concepts
and notation used here are described in @sc{[Stoy77]}.

@quotation
@emph{Note:} The formal semantics section was written in La@TeX{} which
is incompatible with @TeX{}info.  See pages 34--36 of @sc{[R4RS]}, the
original document from which this was derived.
@end quotation

@menu
* Abstract syntax::
* Domain equations::
* Semantic functions::
* Auxiliary functions::
@end menu

@node Abstract syntax, Domain equations, Formal semantics, Formal semantics
@subsection Abstract syntax

@node Domain equations, Semantic functions, Abstract syntax, Formal semantics
@subsection Domain equations

@node Semantic functions, Auxiliary functions, Domain equations, Formal semantics
@subsection Semantic functions

@node Auxiliary functions,  , Semantic functions, Formal semantics
@subsection Auxiliary functions

@node Formal derived expression types,  , Formal semantics, Formal syntax and semantics
@section derived expression types
@c label{Formal derived expression types}

This section gives rewrite rules for the derived expression types.  By
the application of these rules, any expression can be reduced to a
semantically equivalent expression in which only the primitive
expression types (literal, variable, call, @code{lambda}, @code{if},
@findex if
@findex lambda
@code{set!}) occur.
@findex set!

@ignore
todo
Expressions such as @code{(cond)} aren't legal, but they make the
@c  rewrite rules work.
@end ignore

@c \newcommand{\iet}{\hbox to 2em{\hfil $\equiv$}}  % is equivalent to

@format
@t{(cond (@r{<test>} @r{<sequence>})
      @r{<clause 2>} @dots{})
  @equiv{}  (if @r{<test>}
          (begin @r{<sequence>})
          (cond @r{<clause 2>} @dots{}))

(cond (@r{<test>})
      @r{<clause 2>} @dots{})
  @equiv{}  (or @r{<test>} (cond @r{<clause 2>} @dots{}))

(cond (@r{<test>} => @r{<recipient>})
      @r{<clause 2>} @dots{})
  @equiv{}  (let ((test-result @r{<test>})
            (thunk2 (lambda () @r{<recipient>}))
            (thunk3 (lambda () (cond @r{<clause 2>} @dots{}))))
        (if test-result
            ((thunk2) test-result)
            (thunk3)))

(cond (else @r{<sequence>}))
  @equiv{}  (begin @r{<sequence>})

(cond)
  @equiv{}  @r{<some expression returning an unspecified value>}

(case @r{<key>}
  ((d1 @dots{}) @r{<sequence>})
  @dots{})
  @equiv{}  (let ((key @r{<key>})
            (thunk1 (lambda () @r{<sequence>}))
            @dots{})
        (cond ((@r{<memv>} key '(d1 @dots{})) (thunk1))
               @dots{}))

(case @r{<key>}
  ((d1 @dots{}) @r{<sequence>})
  @dots{}
  (else f1 f2 @dots{}))
  @equiv{}  (let ((key @r{<key>})
            (thunk1 (lambda () @r{<sequence>}))
            @dots{}
            (elsethunk (lambda () f1 f2 @dots{})))
        (cond ((@r{<memv>} key '(d1 @dots{})) (thunk1))
               @dots{}
              (else (elsethunk))))}
@end format

@noindent
where @r{<memv>} is an expression evaluating to the @code{memv}
procedure.
@findex memv

@format
@t{(and)              @equiv{}  @code{#t}
(and @r{<test>})        @equiv{}  @r{<test>}
(and @r{<test 1>} @r{<test 2>} @dots{})
  @equiv{}  (let ((x @r{<test 1>})
            (thunk (lambda () (and @r{<test 2>} @dots{}))))
        (if x (thunk) x))

(or)               @equiv{}  @code{#f}
(or @r{<test>})         @equiv{}  @r{<test>}
(or @r{<test 1>} @r{<test 2>} @dots{})
  @equiv{}  (let ((x @r{<test 1>})
            (thunk (lambda () (or @r{<test 2>} @dots{}))))
        (if x x (thunk)))

(let ((@r{<variable 1>} @r{<init 1>}) @dots{})
  @r{<body>})
  @equiv{}  ((lambda (@r{<variable 1>} @dots{}) @r{<body>}) @r{<init 1>} @dots{})

(let* () @r{<body>})
  @equiv{}  ((lambda () @r{<body>}))
(let* ((@r{<variable 1>} @r{<init 1>})
       (@r{<variable 2>} @r{<init 2>})
       @dots{})
  @r{<body>})
  @equiv{}  (let ((@r{<variable 1>} @r{<init 1>}))
        (let* ((@r{<variable 2>} @r{<init 2>})
               @dots{})
          @r{<body>}))

(letrec ((@r{<variable 1>} @r{<init 1>})
         @dots{})
  @r{<body>})
  @equiv{}  (let ((@r{<variable 1>} @r{<undefined>})
            @dots{})
         (let ((@r{<temp 1>} @r{<init 1>})
               @dots{})
           (set! @r{<variable 1>} @r{<temp 1>})
           @dots{})
         @r{<body>})}
@end format

@noindent
where @r{<temp 1>}, @r{<temp 2>}, @dots{} are variables, distinct
from @r{<variable 1>}, @dots{}, that do not free occur in the
original @r{<init>} expressions, and @r{<undefined>} is an expression
which returns something that when stored in a location makes it an
error to try to obtain the value stored in the location.  (No such
expression is defined, but one is assumed to exist for the purposes of this
rewrite rule.)  The second @code{let} expression in the expansion is not
@findex let
strictly necessary, but it serves to preserve the property that the
@r{<init>} expressions are evaluated in an arbitrary order.

@format
@t{
(begin @r{<sequence>})
  @equiv{}  ((lambda () @r{<sequence>}))}
@end format

@noindent
@findex begin
The following alternative expansion for @code{begin} does not make use
of the ability to write more than one expression in the body of a lambda
expression.  In any case, note that these rules apply only if
@r{<sequence>} contains no definitions.

@format
@t{(begin @r{<expression>})  @equiv{}  @r{<expression>}
(begin @r{<command>} @r{<sequence>})
  @equiv{}  ((lambda (ignore thunk) (thunk))
       @r{<command>}
       (lambda () (begin @r{<sequence>})))}
@end format

@findex do
The following expansion for @code{do} is simplified by the assumption
that no @r{<step>} is omitted.  Any @code{do} expression in which a
@r{<step>} is omitted can be replaced by an equivalent @code{do}
expression in which the corresponding @r{<variable>} appears as
the @r{<step>}.

@format
@t{(do ((@r{<variable 1>} @r{<init 1>} @r{<step 1>})
     @dots{})
    (@r{<test>} @r{<sequence>})
  @r{<command 1>} @dots{})
  @equiv{}  (letrec ((@r{<loop>}
                (lambda (@r{<variable 1>} @dots{})
                  (if @r{<test>}
                      (begin @r{<sequence>})
                      (begin @r{<command 1>}
                             @dots{}
                             (@r{<loop>} @r{<step 1>} @dots{}))))))
        (@r{<loop>} @r{<init 1>} @dots{}))}
@end format

@noindent
where @r{<loop>} is any variable which is distinct from
@r{<variable 1>}, @dots{}, and which does not occur free in the @code{do}
expression.
@findex do

@format
@t{(let @r{<variable 0>} ((@r{<variable 1>} @r{<init 1>}) @dots{})
  @r{<body>})
  @equiv{}  ((letrec ((@r{<variable 0>} (lambda (@r{<variable 1>} @dots{})
                             @r{<body>})))
          @r{<variable 0>})
       @r{<init 1>} @dots{})

(delay @r{<expression>})
  @equiv{}  (@r{<make-promise>} (lambda () @r{<expression>}))}
@end format

@noindent
where @r{<make-promise>} is an expression evaluating to some procedure
which behaves appropriately with respect to the @code{force} procedure;
@findex force
see @ref{Control features}.

@c  `a                =  Q1[a]
@c  `(a b c ... . z)  =  `(a . (b c ...))
@c  `(a . b)          =  (append Q*0[a] `b)
@c  `(a)              =  Q*0[a]
@c  Q*0[a]           =  (list 'a)
@c  Q*0[,a]          =  (list a)
@c  Q*0[,@a]         =  a
@c  Q*0[`a]          =  (list 'quasiquote Q*1[a])
@c  `#(a b ...)       =  (list->vector `(a b ...))
@c   ugh.

@node Notes, Example, Formal syntax and semantics, Top
@unnumbered NOTES
@c @menu
@c * Language changes::
@c @end menu
@c @node Language changes
@heading Language changes

@ignore
todo
Perhaps this section should be made to disappear.
Can these remarks be moved somewhere else?
@end ignore
@c label{differences}

This section enumerates the changes that have been made to Scheme since
the ``Revised(3) report'' @sc{[R3RS]} was published.

@itemize @bullet
@item Although implementations may extend Scheme, they must offer
a syntactic mode that adds no reserved words and preempts no lexical conventions
of Scheme.

@item Implementations may report violations of
implementation restrictions.

@item It is no longer specified whether the empty list counts as true
or as false in conditional expressions.  It should be noted that the
IEEE standard for Scheme requires the empty list to count as true
@sc{[IEEEScheme]}.

@item The sets defined by @code{boolean?}, @code{pair?}, @code{symbol?},
@code{number?}, @code{char?}, @code{string?}, @code{vector?},and
@code{procedure?} are required to be disjoint.
@findex pair?
@findex boolean?
@findex symbol?
@findex vector?
@findex string?
@findex char?
@findex procedure?
@findex number?

@item The variables bound by a @code{lambda}, @code{let}, @code{letrec},
and @code{do} must not contain duplicates.
@findex let
@findex letrec
@findex lambda
@findex do

@item Nested @code{begin} expressions containing definitions are treated
@findex begin
as a sequence of definitions.

@item The @code{eqv?} procedure is no longer required to be true of any
@findex eqv?
two empty strings or two empty vectors.

@item The syntax of numerical constants has been changed, and the exactness
implied by each syntax has been specified.

@item The semantics of many numerical procedures have been clarified.

@item @code{Rationalize} has been restricted to two arguments and its
@findex rationalize
specification clarified.

@item The @code{number->string} and @code{string->number} procedures
@findex string->number
@findex number->string
have been changed.

@item @code{Integer->char} now requires an exact integer argument.
@findex integer->char

@item The specification of the @code{force} procedure has been
@findex force
weakened.  The previous specification was unimplementable.

@item Variables removed: @code{t}, @code{nil}.
@findex nil
@findex t

@item Procedures removed: @code{approximate}, @code{last-pair}.
@findex last-pair
@findex approximate

@item Procedures added: @code{list?}, @code{peek-char}.
@findex peek-char
@findex list?

@item Syntaxes made essential: @code{case}, @code{and}, @code{or},
@findex or
@findex and
@findex case
@code{quasiquote}.
@findex quasiquote

@item Procedures made essential:
@end itemize

@lisp
reverse        char-ci=?        make-string
max            char-ci<?        string-set!
min            char-ci>?        string-ci=?
modulo         char-ci<=?       string-ci<?
gcd            char-ci>=?       string-ci>?
lcm            char-alphabetic? string-ci<=?
floor          char-numeric?    string-ci>=?
ceiling        char-whitespace? string-append
truncate       char-lower-case? open-input-file
round          char-upper-case? open-output-file
number->string char-upcase      close-input-port
string->number char-downcase    close-output-port
@end lisp

@itemize @bullet
@item Procedures required to accept more general numbers of arguments:
@code{append}, @code{+}, @code{*}, @code{-} (one argument),
@findex -
@findex *
@findex +
@code{/} (one argument), @code{=}, @code{<}, @code{>}, @code{<=}, @code{>=},
@findex /
@findex append
@code{map}, @code{for-each}.
@findex >=
@findex >
@findex <
@findex map
@findex =
@findex for-each

@item A macro facility has been added as an appendix to this report.

@ignore
todo
@item @code{Call-with-input-file} and @code{call-with-output-file} renamed
to @code{call-with-input-port} and @code{call-with-output-port}
@findex call-with-output-port
@findex call-with-input-port
@end ignore

@end itemize

@ignore
todo
@c node Comparison with the dialect used in @sc{[SICP]},
@c heading Comparison with the dialect used in @sc{[SICP]}
Compare with S&ICP: simple renamings like @code{print}; easily
implemented things like @code{cons-stream}; more grave and controversial
omissions like @code{eval} and @code{make-environment}.
@end ignore

@c  I think the comparison with S&ICP is no longer so important.
@c  A comparison with IEEE Scheme might now be in order, though.
@c  -- Will, 1991.

@c %R4%
@c @node Keywords as variable names
@c @heading Keywords as variable names

@c Some implementations allow arbitrary syntactic
@c keywords
@c @cindex keyword
@c @cindex syntactic keyword
@c to be used as variable
@c names, instead of reserving them, as this report would have
@c it.
@c @cindex variable
@c  But this creates ambiguities in the interpretation
@c of expressions: for example, in the following, it's not clear whether
@c the expression @code{(if 1 2 3)} should be treated as a procedure call or
@c as a conditional.

@c @lisp
@c (define if list)
@c (if 1 2 3)               @result{}  2 @emph{or} (1 2 3)
@c @end lisp

@c These ambiguities are usually resolved in some consistent way within any
@c given implementation, but no particular treatment stands out as being
@c clearly superior to any other, so these situations were excluded for the
@c purposes of this report.

@c %R4%
@c @node Macros
@c @heading Macros

@c Scheme does not have any standard facility for defining new kinds of
@c expressions.
@c @cindex macros

@c vest
@c The ability to alter the syntax of the language creates
@c numerous problems.  All current implementations of Scheme have macro
@c facilities that solve those problems to one degree or another, but the
@c solutions are quite different and it isn't clear at this time which
@c solution is best, or indeed whether any of the solutions are truly
@c adequate.  Rather than standardize, we are encouraging implementations
@c to continue to experiment with different solutions.

@c vest
@c The main problems with traditional macros are: They must be
@c defined to the system before any code using them is loaded; this is a
@c common source of obscure bugs.  They are usually global; macros can be
@c made to follow lexical scope rules
@ignore
todo
flushed: ``as in Common
@c Lisp's @code{macrolet}''; OK?
@end ignore
@c , but many people find the resulting scope rules
@c confusing.  Unless they are written very carefully, macros are
@c vulnerable to inadvertant capture of free variables; to get around this,
@c for example, macros may have to generate code in which procedure values
@c appear as quoted constants.  There is a similar problem with syntactic
@c keywords if the keywords of special forms are not reserved.  If keywords
@c are reserved, then either macros introduce new reserved words,
@c invalidating old code, or else special forms defined by the programmer
@c do not have the same status as special forms defined by the system.

@ignore
todo
Refer to Pitman's special forms paper.
@end ignore
@ignore
todo
Pitman sez: Discuss importance of having a small number of special forms
@c so that programs can inspect each other.
@end ignore
@ignore
todo
Move cwcc history back here? --- Andy Cromarty is concerned about
confusion over who the audience is.
@end ignore
@ignore
todo
Cromarty:
23. NOTES, p.35ff.: This material should stay somehow.  We need to
    make it clear that R$^3$ Scheme is not being touted as Yet Another
    Ultimate Solution To The Programming Language Problem, but rather
    as a snapshot of a *process* of good design, for which not all
    answers have yet been found.  We also ought to use the opportunity
    for publicity afforded us by SIGPLAN to advertise some of the thorny
    unsolved problems that need further research, and encourage
    language designers to work on them.
@end ignore
@c page

@node Example, Macros, Notes, Top
@unnumbered Example
@c extrapart{Example} % -*- Mode: Lisp; Package: SCHEME; Syntax: Common-lisp -*-

@code{Integrate-system} integrates the system
@findex integrate-system

@center @i{y_k' = f_k(y_1, y_2, @dots{}, y_n), ; k = 1, @dots{}, n}

@noindent
of differential equations with the method of Runge-Kutta.

The parameter @code{system-derivative} is a function that takes a system
state (a vector of values for the state variables y_1, @dots{}, y_n)
and produces a system derivative (the values y_1', @dots{}, y_n').
The parameter @code{initial-state} provides an initial
system state, and @code{h} is an initial guess for the length of the
integration step.

The value returned by @code{integrate-system} is an infinite stream of
@findex integrate-system
system states.

@format
@t{(define integrate-system
  (lambda (system-derivative initial-state h)
    (let ((next (runge-kutta-4 system-derivative h)))
      (letrec ((states
                (cons initial-state
                      (delay (map-streams next
                                          states)))))
        states))))}
@end format

@code{Runge-Kutta-4} takes a function, @code{f}, that produces a
@findex runge-Kutta-4
system derivative from a system state.  @code{Runge-Kutta-4}
@findex runge-Kutta-4
produces a function that takes a system state and
produces a new system state.

@format
@t{(define runge-kutta-4
  (lambda (f h)
    (let ((*h (scale-vector h))
          (*2 (scale-vector 2))
          (*1/2 (scale-vector (/ 1 2)))
          (*1/6 (scale-vector (/ 1 6))))
      (lambda (y)
        ;; y @r{is a system state}
        (let* ((k0 (*h (f y)))
               (k1 (*h (f (add-vectors y (*1/2 k0)))))
               (k2 (*h (f (add-vectors y (*1/2 k1)))))
               (k3 (*h (f (add-vectors y k2)))))
          (add-vectors y
            (*1/6 (add-vectors k0
                               (*2 k1)
                               (*2 k2)
                               k3))))))))
@c |--------------------------------------------------|

(define elementwise
  (lambda (f)
    (lambda vectors
      (generate-vector
        (vector-length (car vectors))
        (lambda (i)
          (apply f
                 (map (lambda (v) (vector-ref  v i))
                      vectors)))))))

@c |--------------------------------------------------|
(define generate-vector
  (lambda (size proc)
    (let ((ans (make-vector size)))
      (letrec ((loop
                (lambda (i)
                  (cond ((= i size) ans)
                        (else
                         (vector-set! ans i (proc i))
                         (loop (+ i 1)))))))
        (loop 0)))))

(define add-vectors (elementwise +))

(define scale-vector
  (lambda (s)
    (elementwise (lambda (x) (* x s)))))}
@end format

@code{Map-streams} is analogous to @code{map}: it applies its first
@findex map
@findex map-streams
argument (a procedure) to all the elements of its second argument (a
stream).

@format
@t{(define map-streams
  (lambda (f s)
    (cons (f (head s))
          (delay (map-streams f (tail s))))))}
@end format

Infinite streams are implemented as pairs whose car holds the first
element of the stream and whose cdr holds a promise to deliver the rest
of the stream.

@format
@t{(define head car)
(define tail
  (lambda (stream) (force (cdr stream))))}
@end format

@c @sp 10
@findex integrate-system
The following illustrates the use of @code{integrate-system} in
integrating the system

@ifinfo
@example
   d v            v
      C            C
C (----) = - i  - --
   d t        L   R

   d i
      L
L (----) = v
   d t      C
@end example
@end ifinfo

@iftex
@center @i{C (dvC / dt) = -iL - (vC / R)}

@center @i{L (diL / dt) = vC}
@end iftex
@noindent

@noindent
which models a damped oscillator.

@format
@t{(define damped-oscillator
  (lambda (R L C)
    (lambda (state)
      (let ((Vc (vector-ref state 0))
            (Il (vector-ref state 1)))
        (vector (- 0 (+ (/ Vc (* R C)) (/ Il C)))
                (/ Vc L))))))

(define the-states
  (integrate-system
     (damped-oscillator 10000 1000 .001)
     '#(1 0)
     .01))}
@end format

@ignore
todo
Show some output?
@end ignore

@c  (letrec ((loop (lambda (s)
@c                 (newline)
@c                 (write (head s))
@c                 (loop (tail s)))))
@c    (loop the-states))

@c  #(1 0)
@c  #(0.99895054 9.994835e-6)
@c  #(0.99780226 1.9978681e-5)
@c  #(0.9965554 2.9950552e-5)
@c  #(0.9952102 3.990946e-5)
@c  #(0.99376684 4.985443e-5)
@c  #(0.99222565 5.9784474e-5)
@c  #(0.9905868 6.969862e-5)
@c  #(0.9888506 7.9595884e-5)
@c  #(0.9870173 8.94753e-5)

@node Macros, Bibliography and references, Example, Top
@appendix Macros

This appendix describes an extension to Scheme that allows programs
to define and use new derived expression types.
A derived expression type that has been defined using this extension
is called a @emph{macro}.
@cindex @w{macro}

Derived expression types introduced using this extension have
the syntax
@lisp
(@r{<keyword>} @r{<datum>}@r{*})
@end lisp
where @r{<keyword>} is an identifier that uniquely determines the
expression type.  This identifier is called the @emph{syntactic
keyword}, or simply @emph{keyword},
@cindex syntactic keyword
@cindex keyword
of the macro.
@cindex macro keyword
The number of the @r{<datum>}s, and their syntax, depends on the
expression type.

Each instance of a macro is called a @emph{use}
@cindex macro use
of the macro.
The set of rules, or more generally the procedure, that specifies
how a use of a macro is transcribed into a more primitive expression
is called the @emph{transformer}
@cindex macro transformer
of the macro.

The extension described here consists of three parts:

@itemize @bullet

@item A set of expressions used to establish that certain identifiers
are macro keywords, associate them with macro transformers, and control
the scope within which a macro is defined,

@item a convenient pattern language that makes it easy to write
transformers for most macros, and

@item a compatible low-level macro facility for writing macro
transformers that cannot be expressed by the pattern language.

@end itemize

With this extension, there are no reserved identifiers.  The syntactic
keyword of a macro may shadow variable bindings, and local variable
bindings may shadow keyword bindings.
@cindex keyword
All macros
defined using the pattern language are ``hygienic'' and
``referentially transparent'':
@cindex @w{hygienic}
@cindex @w{referentially transparent}

@itemize @bullet

@item If a macro transformer inserts a binding for an identifier
(variable or keyword), the identifier will in effect be renamed
throughout its scope to avoid conflicts with other identifiers.

@item If a macro transformer inserts a free reference to an
identifier, the reference refers to the binding that was visible
where the transformer was specified, regardless of any local
bindings that may surround the use of the macro.

@end itemize

@c The low-level facility permits non-hygienic macros to be written,
@c and may be used to implement the high-level pattern language.

This appendix is divided into three major sections.  The first
section describes the expressions and definitions used to
introduce macros, i.e. to bind identifiers to macro
transformers.

The second section describes the pattern language.  This pattern
language is sufficient to specify most macro transformers, including
those for all the derived expression types from
@ref{Derived expression types}.  The primary limitation of the pattern
language is that it is thoroughly hygienic, and thus cannot express
macros that bind identifiers implicitly.

The third section describes a low-level macro facility that could be
used to implement the pattern language described in the second
section.  This low-level facility is also capable of expressing
non-hygienic macros and other macros whose transformers cannot be
described by the pattern language, and is important as an example of a
more powerful facility that can co-exist with the high-level pattern
language.

The particular low-level facility described in the third
section is but one of several low-level facilities that have been
designed and implemented to complement the pattern language described
in the second section.  The design of such low-level macro facilities
remains an active area of research, and descriptions of alternative
low-level facilities will be published in subsequent documents.

@c  The fourth section describes some features that would make the
@c  low-level macro facility easier to use directly.

@menu
* Binding syntactic keywords::
* Pattern language::
* A compatible low-level macro facility::
* Acknowledgements:Macro Acknowledgements
@end menu

@node Binding syntactic keywords, Pattern language, Macros, Macros
@appendixsec Binding syntactic keywords
@c label{Binding syntactic keywords}

@code{Define-syntax}, @code{let-syntax}, and @code{letrec-syntax} are
analogous to @code{define}, @code{let}, and @code{letrec}, but they bind
syntactic keywords to macro transformers instead of binding variables
to locations that contain values.  Furthermore, there is no @code{
define-syntax} analogue of the internal definitions described in
@ref{Internal definitions}.

@emph{Rationale:}  As discussed below, the syntax and scope rules for definitions
give rise to syntactic ambiguities when syntactic keywords are
not reserved.
Further ambiguities would arise if @code{define-syntax}
were permitted at the beginning of a @r{<body>}, with scope
rules analogous to those for internal definitions.
@c end rationale

These new expression types and the pattern language described in
@ref{Pattern language} are added to Scheme by augmenting the
BNF in @ref{Formal syntax} with the following new productions.  Note
that the identifier @code{...} used in some of these productions is not
a metasymbol.

@c grammar
@format
@r{<expression>} @expansion{} @r{<macro use>}
     | @r{<macro block>}

@r{<macro use>} @expansion{} (@r{<keyword>} @r{<datum>}@r{*})
@r{<keyword>} @expansion{} @r{<identifier>}

@r{<macro block>} @expansion{}
      (let-syntax (@r{<syntax spec>}@r{*}) @r{<body>})
     | (letrec-syntax (@r{<syntax spec>}@r{*}) @r{<body>})
@r{<syntax spec>} @expansion{} (@r{<keyword>} @r{<transformer spec>})
@r{<transformer spec>} @expansion{}
      (syntax-rules (@r{<identifier>}@r{*}) @r{<syntax rule>}@r{*})
@r{<syntax rule>} @expansion{} (@r{<pattern>} @r{<template>})
@r{<pattern>} @expansion{} @r{<pattern identifier>}
     | (@r{<pattern>}@r{*})
     | (@r{<pattern>}@r{+} . @r{<pattern>})
     | (@r{<pattern>}@r{*} @r{<pattern>} @r{<ellipsis>})
     | @r{<pattern datum>}
@r{<pattern datum>} @expansion{} @r{<vector>}
     | @r{<string>}
     | @r{<character>}
     | @r{<boolean>}
     | @r{<number>}
@r{<template>} @expansion{} @r{<pattern identifier>}
     | (@r{<template element>}@r{*})
     | (@r{<template element>}@r{+} . @r{<template>})
     | @r{<template datum>}
@r{<template element>} @expansion{} @r{<template>}
     | @r{<template>} @r{<ellipsis>}
@r{<template datum>} @expansion{} @r{<pattern datum>}
@r{<pattern identifier>} @expansion{} @r{<any identifier except @code{...}>}
@r{<ellipsis>} @expansion{} @r{<the identifier @code{...}>}

@group
@r{<command or definition>} @expansion{} @r{<syntax definition>}
@r{<syntax definition>} @expansion{}
      (define-syntax @r{<keyword>} @r{<transformer spec>})
     | (begin @r{<syntax definition>}@r{*})
@end group
@end format

@c  It is an error for a program to contain more than one top-level
@c  @r{<definition>} or @r{<syntax definition>} of any identifier.

@c  [I flushed this because it isn't an error for a program to
@c  contain more than one top-level definition of an identifier,
@c  and I didn't want to introduce any gratuitous incompatibilities
@c  with the existing Scheme language. -- Will]

Although macros may expand into definitions in any context that permits
definitions, it is an error for a definition to shadow a syntactic
keyword whose meaning is needed to determine whether some definition in
the group of top-level or internal definitions that contains the
shadowing definition is in fact a definition, or is needed to determine
the boundary between the group and the expressions that follow the
group.  For example, the following are errors:

@lisp
(define define 3)

(begin (define begin list))

(let-syntax
  ((foo (syntax-rules ()
          ((foo (proc args ...) body ...)
           (define proc
             (lambda (args ...)
               body ...))))))
  (let ((x 3))
    (foo (plus x y) (+ x y))
    (define foo x)
    (plus foo x)))
@end lisp

@deffn {syntax} syntax {let-syntax} @r{<bindings>} @r{<body>}

@emph{Syntax:}  @r{<Bindings>} should have the form
@lisp
((@r{<keyword>} @r{<transformer spec>}) @dots{})
@end lisp
@c where each @r{<keyword>} is an identifier,
@c each @r{<transformer spec>} is an instance of @code{syntax-rules}, and
Each @r{<keyword>} is an identifier,
each @r{<transformer spec>} is an instance of @code{syntax-rules}, and
@r{<body>} should be a sequence of one or more expressions.  It is an error
for a @r{<keyword>} to appear more than once in the list of keywords
being bound.

@emph{Semantics:}  The @r{<body>} is expanded in the syntactic environment
obtained by extending the syntactic environment of the
@code{let-syntax} expression with macros whose keywords are
the @r{<keyword>}s, bound to the specified transformers.
Each binding of a @r{<keyword>} has @r{<body>} as its region.

@lisp
(let-syntax ((when (syntax-rules ()
                     ((when test stmt1 stmt2 ...)
                      (if test
                          (begin stmt1
                                 stmt2 ...))))))
  (let ((if #t))
    (when if (set! if 'now))
    if))                    @result{}  now

(let ((x 'outer))
  (let-syntax ((m (syntax-rules () ((m) x))))
    (let ((x 'inner))
      (m))))                @result{}  outer
@end lisp

@end deffn

@deffn {syntax} syntax {letrec-syntax} @r{<bindings>} @r{<body>}

@emph{Syntax:}  Same as for @code{let-syntax}.

@emph{Semantics:}   The @r{<body>} is expanded in the syntactic environment obtained by
extending the syntactic environment of the @code{letrec-syntax}
expression with macros whose keywords are the
@r{<keyword>}s, bound to the specified transformers.
Each binding of a @r{<keyword>} has the @r{<bindings>}
as well as the @r{<body>} within its region,
so the transformers can
transcribe expressions into uses of the macros
introduced by the @code{letrec-syntax} expression.

@lisp
(letrec-syntax
  ((or (syntax-rules ()
         ((or) #f)
         ((or e) e)
         ((or e1 e2 ...)
          (let ((temp e1))
            (if temp
                temp
                (or e2 ...)))))))
  (let ((x #f)
        (y 7)
        (temp 8)
        (let odd?)
        (if even?))
    (or x
        (let temp)
        (if y)
        y)))                @result{}  7
@end lisp

@end deffn

@deffn {syntax} define-syntax @r{<keyword>} @r{<transformer spec>}

@emph{Syntax:}  The @r{<keyword>} is an identifier, and the @r{<transformer
spec>} should be an instance of @code{syntax-rules}.

@emph{Semantics:}  The top-level syntactic environment is extended by binding the
@r{<keyword>} to the specified transformer.

@lisp
(define-syntax let*
  (syntax-rules ()
    ((let* () body1 body2 ...)
     (let () body1 body2 ...))
    ((let* ((name1 val1) (name2 val2) ...)
       body1 body2 ...)
     (let ((name1 val1))
       (let* ((name2 val2) ...)
         body1 body2 ...)))))
@end lisp

@end deffn

@node Pattern language, A compatible low-level macro facility, Binding syntactic keywords, Macros
@appendixsec Pattern language
@c label{Pattern language}

@deffn {syntax} syntax-rules @r{<literals>} @r{<syntax rule>} @dots{}

@emph{Syntax:}  @r{<Literals>} is a list of identifiers, and each @r{<syntax rule>}
should be of the form
@lisp
(@r{<pattern>} @r{<template>})
@end lisp
where the @r{<pattern>} and @r{<template>} are as in the grammar
above.

@emph{Semantics:}  An instance of @code{syntax-rules} produces a new macro
transformer by specifying a sequence of hygienic rewrite rules.  A use
of a macro whose keyword is associated with a transformer specified by
@code{syntax-rules} is matched against the patterns contained in the
@r{<syntax rule>}s, beginning with the leftmost @r{<syntax rule>}.
When a match is found, the macro use is transcribed hygienically
according to the template.

Each pattern begins with the keyword for the macro.  This keyword
is not involved in the matching and is not considered a pattern
variable or literal identifier.

@emph{Rationale:}  The scope of the keyword is determined by the expression or syntax
definition that binds it to the associated macro transformer.
If the keyword were a pattern variable or literal identifier, then
the template that follows the pattern would be within its scope
regardless of whether the keyword were bound by @code{let-syntax}
or by @code{letrec-syntax}.
@c end rationale

An identifier that appears in the pattern of a @r{<syntax rule>} is
a pattern variable, unless it is the keyword that begins the pattern,
is listed in @r{<literals>}, or is the identifier ``@code{...}''.
Pattern variables match arbitrary input elements and
are used to refer to elements of the input in the template.  It is an
error for the same pattern variable to appear more than once in a
@r{<pattern>}.

Identifiers that appear in @r{<literals>} are interpreted as literal
identifiers to be matched against corresponding subforms of the input.
A subform
in the input matches a literal identifier if and only if it is an
identifier
and either both its occurrence in the macro expression and its
occurrence in the macro definition have the same lexical binding, or
the two identifiers are equal and both have no lexical binding.

@c  [Bill Rozas suggested the term "noise word" for these literal
@c  identifiers, but in their most interesting uses, such as a setf
@c  macro, they aren't noise words at all. -- Will]

A subpattern followed by @code{...} can match zero or more elements of the
input.  It is an error for @code{...} to appear in @r{<literals>}.
Within a pattern the identifier @code{...} must follow the last element of
a nonempty sequence of subpatterns.

More formally, an input form @var{F} matches a pattern @var{P} if and only if:

@itemize @bullet
@item @var{P} is a pattern variable; or

@item @var{P} is a literal identifier and @var{F} is an identifier with the same
      binding; or

@item @var{P} is a pattern list @code{(@var{P1} @dots{} @var{Pn})} and @var{F} is a
      list of @var{n}
      forms that match @var{P1} through @var{Pn}, respectively; or

@item @var{P} is an improper pattern list
      @code{(@var{P1} @var{P2} @dots{} @var{Pn} . @var{Q})}
      and @var{F} is a list or
      improper list of @var{n} or more forms that match @var{P1} through @var{Pn},
      respectively, and whose @var{n}th ``cdr'' matches @var{Q}; or

@item @var{P} is @c a pattern list
      of the form
      @code{(@var{P1} @dots{} @var{Pn} @var{Q} @r{<ellipsis>})}
      where @r{<ellipsis>} is the identifier @code{@dots{}}
      and @var{F} is
      a proper list of at least @var{n} elements, the first @var{n} of which match
      @var{P1} through @var{Pn}, respectively, and each remaining element of @var{F}
      matches @var{Q}; or

@item @var{P} is a pattern datum and @var{F} is equal to @var{P} in the sense of
      the @code{equal?} procedure.
@end itemize

It is an error to use a macro keyword, within the scope of its
binding, in an expression that does not match any of the patterns.

When a macro use is transcribed according to the template of the
matching @r{<syntax rule>}, pattern variables that occur in the
template are replaced by the subforms they match in the input.
Pattern variables that occur in subpatterns followed by one or more
instances of the identifier
@code{...} are allowed only in subtemplates that are
followed by as many instances of @code{...}.
They are replaced in the
output by all of the subforms they match in the input, distributed as
indicated.  It is an error if the output cannot be built up as
specified.

@c %% This description of output construction is very vague.  It should
@c %% probably be formalized, but that is not easy...

Identifiers that appear in the template but are not pattern variables
or the identifier
@code{...} are inserted into the output as literal identifiers.  If a
literal identifier is inserted as a free identifier then it refers to the
binding of that identifier within whose scope the instance of
@code{syntax-rules} appears.
If a literal identifier is inserted as a bound identifier then it is
in effect renamed to prevent inadvertent captures of free identifiers.

@lisp
(define-syntax let
  (syntax-rules ()
    ((let ((name val) ...) body1 body2 ...)
     ((lambda (name ...) body1 body2 ...)
      val ...))
    ((let tag ((name val) ...) body1 body2 ...)
     ((letrec ((tag (lambda (name ...)
                      body1 body2 ...)))
        tag)
      val ...))))

(define-syntax cond
  (syntax-rules (else =>)
    ((cond (else result1 result2 ...))
     (begin result1 result2 ...))
    ((cond (test => result))
     (let ((temp test))
       (if temp (result temp))))
    ((cond (test => result) clause1 clause2 ...)
     (let ((temp test))
       (if temp
           (result temp)
           (cond clause1 clause2 ...))))
    ((cond (test)) test)
    ((cond (test) clause1 clause2 ...)
     (or test (cond clause1 clause2 ...)))
    ((cond (test result1 result2 ...))
     (if test (begin result1 result2 ...)))
    ((cond (test result1 result2 ...)
           clause1 clause2 ...)
     (if test
         (begin result1 result2 ...)
         (cond clause1 clause2 ...)))))

(let ((=> #f))
  (cond (#t => 'ok)))       @result{}  ok
@end lisp

The last example is not an error because the local variable @code{=>}
is renamed in effect, so that its use is distinct from uses of the top
level identifier @code{=>} that the transformer for @code{cond} looks
for.  Thus, rather than expanding into

@lisp
(let ((=> #f))
  (let ((temp #t))
    (if temp ('ok temp))))
@end lisp

@noindent
which would result in an invalid procedure call, it expands instead
into

@lisp
(let ((=> #f))
  (if #t (begin => 'ok)))
@end lisp

@end deffn

@node A compatible low-level macro facility, Macro Acknowledgements, Pattern language, Macros
@appendixsec A compatible low-level macro facility
@c label{A compatible low-level macro facility}

Although the pattern language provided by @code{syntax-rules} is the
preferred way to specify macro transformers, other low-level
facilities may be provided to specify more complex macro transformers.
In fact, @code{syntax-rules} can itself be defined as a macro using the
low-level facilities described in this section.

The low-level macro facility described here introduces @code{syntax}
as a new syntactic keyword analogous to @code{quote}, and allows a
@r{<transformer spec>} to be any expression.  This is accomplished by
adding the following two productions to the productions in
@ref{Formal syntax} and in @ref{Binding syntactic keywords} above.

@c grammar
@format
@r{<expression>} @expansion{} (syntax @r{<datum>})
@r{<transformer spec>} @expansion{} @r{<expression>}
@end format

The low-level macro system also adds the following procedures:

@lisp
unwrap-syntax          identifier->symbol
identifier?            generate-identifier
free-identifier=?      construct-identifier
bound-identifier=?
@end lisp

Evaluation of a program proceeds in two logical steps.  First the
program is converted into an intermediate language via macro-expansion,
and then the result of macro expansion is evaluated.  When it is
necessary to distinguish the second stage of this process from the
full evaluation process, it is referred to as ``execution.''

Syntax definitions, either lexical or global, cause an identifier to
be treated as a keyword within the scope of the binding.  The keyword
is associated with a transformer, which may be created implicitly
using the pattern language of @code{syntax-rules} or explicitly using
the low-level facilities described below.

Since a transformer spec must be fully evaluated during the
course of expansion, it is necessary to specify the environment in
which this evaluation takes place.  A transformer spec is
expanded in the same environment as that in which the program is being
expanded, but is executed in an environment that is distinct from the
environment in which the program is executed.  This execution
environment distinction is important only for the resolution of global
variable references and assignments.  In what follows, the environment
in which transformers are executed is called the standard transformer
environment and is assumed to be a standard Scheme environment.

Since part of the task of hygienic macro expansion is to resolve
identifier references, the fact that transformers are expanded in the
same environment as the program means that identifier bindings in the
program can shadow identifier uses within transformers.  Since
variable bindings in the program are not available at the time the
transformer is executed, it is an error for a transformer to reference
or assign them.  However, since keyword bindings are available during
expansion, lexically visible keyword bindings from the program may be
used in macro uses in a transformer.

When a macro use is encountered, the macro transformer associated with
the macro keyword is applied to a representation of the macro
expression.  The result returned by the macro transformer replaces the
original expression and is expanded once again.  Thus macro expansions
may themselves be or contain macro uses.

The syntactic representation passed to a macro transformer
encapsulates information about the structure of the represented form
and the bindings of the identifiers it contains.  These syntax objects
can be traversed and examined using the procedures described below.
The output of a transformer may be built up using the usual Scheme
list constructors, combining pieces of the input with new syntactic
structures.

@deffn {syntax} syntax @r{<datum>}

@emph{Syntax:}  The @r{<datum>} may be any external representation of a Scheme
object.

@emph{Semantics:}  @code{Syntax} is the syntactic analogue of @code{quote}.  It creates a
syntactic representation of @r{<datum>} that, like an argument to a
transformer, contains information about the bindings for identifiers
contained in @r{<datum>}.  The binding for an identifier introduced
by @code{syntax} is the closest lexically visible binding.  All
variables and keywords introduced by transformers must be created by
@code{syntax}.  It is an error to insert a symbol in the output of a
transformation procedure unless it is to be part of a quoted datum.

@lisp
(symbol? (syntax x))        @result{} #f

(let-syntax ((car (lambda (x) (syntax car))))
  ((car) '(0)))             @result{} 0

(let-syntax
  ((quote-quote
    (lambda (x) (list (syntax quote) 'quote))))
  (quote-quote))            @result{} quote

(let-syntax
  ((quote-quote
    (lambda (x) (list 'quote 'quote))))
  (quote-quote))            @result{} @emph{error}
@end lisp

The second @code{quote-quote} example results in an error because two raw
symbols are being inserted in the output.  The quoted @code{quote} in the
first @code{quote-quote} example does not cause an error because it will
be a quoted datum.

@lisp
(let-syntax ((quote-me
              (lambda (x)
                (list (syntax quote) x))))
  (quote-me please))        @result{} (quote-me please)

(let ((x 0))
  (let-syntax ((alpha (lambda (e) (syntax x))))
    (alpha)))               @result{} 0

(let ((x 0))
  (let-syntax ((alpha (lambda (x) (syntax x))))
    (alpha)))               @result{} @emph{error}

(let-syntax ((alpha
              (let-syntax ((beta
                            (syntax-rules ()
                              ((beta) 0))))
                (lambda (x) (syntax (beta))))))
  (alpha))                  @result{} @emph{error}
@end lisp

The last two examples are errors because in both cases a lexically
bound identifier is placed outside of the scope of its binding.
In the first case, the variable @code{x} is placed outside its scope.
In the second case, the keyword @code{beta} is placed outside its
scope.

@lisp
(let-syntax ((alpha (syntax-rules ()
                      ((alpha) 0))))
  (let-syntax ((beta (lambda (x) (alpha))))
    (beta)))                @result{} 0

(let ((list 0))
  (let-syntax ((alpha (lambda (x) (list 0))))
    (alpha)))               @result{} @emph{error}
@end lisp

The last example is an error because the reference to @code{list} in the
transformer is shadowed by the lexical binding for @code{list}.  Since the
expansion process is distinct from the execution of the program,
transformers cannot reference program variables.  On the other hand,
the previous example is not an error because definitions for keywords
in the program do exist at expansion time.

@emph{Note:}  It has been suggested that @code{#'@r{<datum>}} and
@code{#`@r{<datum>}} would be
felicitous abbreviations for @code{(syntax @r{<datum>})}
and @code{(quasisyntax @r{<datum>})}, respectively,
where @code{quasisyntax}, which is not described in this
appendix, would bear the same relationship to @code{syntax}
that @code{quasiquote} bears to @code{quote}.
@c end note

@end deffn

@deffn {procedure} identifier? syntax-object

Returns @code{#t} if @var{syntax-object} represents an identifier,
otherwise returns @code{#f}.

@lisp
(identifier? (syntax x))    @result{} #t
(identifier? (quote x))     @result{} #f
(identifier? 3)             @result{} #f
@end lisp

@end deffn

@deffn {procedure} unwrap-syntax syntax-object

If @var{syntax-object} is an identifier, then it is returned unchanged.
Otherwise @code{unwrap-syntax} converts the outermost structure of
@var{syntax-object} into a
data object whose external representation is the same as that of
@var{syntax-object}.  The result is either an identifier, a pair whose
car
and cdr are syntax objects, a vector whose elements are syntax
objects, an empty list, a string, a boolean, a character, or a number.

@lisp
(identifier? (unwrap-syntax (syntax x)))
                            @result{} #t
(identifier? (car (unwrap-syntax (syntax (x)))))
                            @result{} #t
(unwrap-syntax (cdr (unwrap-syntax (syntax (x)))))
                            @result{} ()
@end lisp

@end deffn

@deffn {procedure} free-identifier=? id1 id2

Returns @code{#t} if the original occurrences of @var{id1}
and @var{id2} have
the same binding, otherwise returns @code{#f}.
@code{free-identifier=?}
is used to look for a literal identifier in the argument to a
transformer, such as @code{else} in a @code{cond} clause.
A macro
definition for @code{syntax-rules} would use @code{free-identifier=?}
to look for literals in the input.

@lisp
(free-identifier=? (syntax x) (syntax x))
                            @result{} #t
(free-identifier=? (syntax x) (syntax y))
                            @result{} r#f

(let ((x (syntax x)))
  (free-identifier=? x (syntax x)))
                            @result{} #f

(let-syntax
  ((alpha
    (lambda (x)
      (free-identifier=? (car (unwrap-syntax x))
                         (syntax alpha)))))
  (alpha))                  @result{} #f

(letrec-syntax
  ((alpha
    (lambda (x)
      (free-identifier=? (car (unwrap-syntax x))
                         (syntax alpha)))))
  (alpha))                  @result{} #t
@end lisp

@end deffn

@deffn {procedure} bound-identifier=? id1 id2

Returns @code{#t} if a binding for one of the two identifiers
@var{id1} and @var{id2} would shadow free references to the other,
otherwise returns @code{#f}.
Two identifiers can be @code{free-identifier=?} without being
@code{bound-identifier=?}  if they were introduced at different
stages in the
expansion process.
@code{Bound-identifier=?} can be used, for example, to
detect duplicate identifiers in bound-variable lists.  A macro
definition of @code{syntax-rules} would use @code{bound-identifier=?}
to look for
pattern variables from the input pattern in the output template.

@lisp
(bound-identifier=? (syntax x) (syntax x))
                            @result{} #t

(letrec-syntax
  ((alpha
    (lambda (x)
      (bound-identifier=? (car (unwrap-syntax x))
                          (syntax alpha)))))
  (alpha))                  @result{} #f
@end lisp

@end deffn

@deffn {procedure} identifier->symbol id

Returns a symbol representing the original name of @var{id}.
@code{Identifier->symbol} is used to examine identifiers that appear in
literal contexts, i.e., identifiers that will appear in quoted
structures.

@lisp
(symbol? (identifier->symbol (syntax x)))
                            @result{} #t
(identifier->symbol (syntax x))
                            @result{} x
@end lisp
@end deffn

@deffn {procedure} generate-identifier
@deffnx {procedure} generate-identifier symbol

Returns a new identifier.
The optional argument to @code{generate-identifier} specifies the
symbolic name of the resulting identifier.  If no argument is
supplied the name is unspecified.

@code{Generate-identifier} is used to introduce bound identifiers into
the output of a transformer.  Since introduced bound identifiers are
automatically renamed, @code{generate-identifier} is necessary only for
distinguishing introduced identifiers when an indefinite number of them
must be generated by a macro.

The optional argument to @code{generate-identifier} specifies the
symbolic name of the resulting identifier.  If no argument is
supplied the name is unspecified.  The procedure
@code{identifier->symbol} reveals the symbolic name of an identifier.

@lisp
(identifier->symbol (generate-identifier 'x))
                            @result{} x

(bound-identifier=? (generate-identifier 'x)
                    (generate-identifier 'x))
                            @result{} #f

(define-syntax set*!
  ; (set*! (@r{<identifier>} @r{<expression>}) ...)
  (lambda (x)
    (letrec
      ((unwrap-exp
        (lambda (x)
          (let ((x (unwrap-syntax x)))
            (if (pair? x)
                (cons (car x)
                      (unwrap-exp (cdr x)))
                x)))))
      (let ((sets (map unwrap-exp
                       (cdr (unwrap-exp x)))))
        (let ((ids (map car sets))
              (vals (map cadr sets))
              (temps (map (lambda (x)
                            (generate-identifier))
                          sets)))
          `(,(syntax let) ,(map list temps vals)
            ,@@(map (lambda (id temp)
                     `(,(syntax set!) ,id ,temp))
                   ids
                   temps)
            #f))))))
@end lisp

@end deffn

@deffn {procedure} construct-identifier id symbol

Creates and returns an identifier named by @var{symbol} that behaves
as if it had been introduced where the identifier @var{id} was
introduced.

@code{Construct-identifier} is used to circumvent hygiene by
creating an identifier that behaves as though it had been
implicitly present in some expression.  For example, the
transformer for a structure
definition macro might construct the name of a field accessor
that does not explicitly appear in a use of the macro,
but can be
constructed from the names of the structure and the field.
If a binding for the field accessor were introduced
by a hygienic transformer, then it would be renamed automatically,
so that the introduced binding would fail to capture any
references to the field accessor that were present in the
input and were intended to be
within the scope of the introduced binding.

Another example is a macro that implicitly binds @code{exit}:

@lisp
(define-syntax loop-until-exit
  (lambda (x)
    (let ((exit (construct-identifier
                 (car (unwrap-syntax x))
                 'exit))
          (body (car (unwrap-syntax
                      (cdr (unwrap-syntax x))))))
      `(,(syntax call-with-current-continuation)
        (,(syntax lambda)
         (,exit)
         (,(syntax letrec)
          ((,(syntax loop)
            (,(syntax lambda) ()
               ,body
               (,(syntax loop)))))
          (,(syntax loop))))))))

(let ((x 0) (y 1000))
  (loop-until-exit
   (if (positive? y)
       (begin (set! x (+ x 3))
              (set! y (- y 1)))
       (exit x))))          @result{} 3000
@end lisp

@end deffn

@node Macro Acknowledgements,  , A compatible low-level macro facility, Macros
@appendixsec Acknowledgements

The extension described in this appendix is the most
sophisticated macro facility that has ever been proposed
for a block-structured programming language.  The main ideas
come from
Eugene Kohlbecker's PhD thesis on hygienic macro expansion
@sc{[Kohlbecker86]}, written under the direction of Dan
Friedman @sc{[hygienic]}, and from the work by Alan Bawden
and Jonathan Rees on syntactic closures @sc{[Bawden88]}.
Pattern-directed macro facilities were popularized by Kent
Dybvig's non-hygienic implementation of @code{extend-syntax}
@sc{[Dybvig87]}.

At the 1988 meeting of this report's authors at Snowbird,
a macro committee consisting of Bawden, Rees, Dybvig,
and Bob Hieb was charged with developing a hygienic macro
facility akin to @code{extend-syntax} but based on syntactic closures.
Chris Hanson implemented a prototype and wrote a paper on his
experience, pointing out that an implementation based on
syntactic closures must determine the syntactic roles of some
identifiers before macro expansion based on textual pattern
matching can make those roles apparent.  William Clinger
observed that Kohlbecker's algorithm amounts to a technique
for delaying this determination, and proposed a more efficient
version of Kohlbecker's algorithm.  Pavel Curtis spoke up for
referentially transparent local macros.  Rees merged syntactic
environments with the modified Kohlbecker's algorithm and
implemented it all, twice @sc{[macrosthatwork]}.

Dybvig and Hieb designed and implemented the low-level
macro facility described above.
Recently Hanson and Bawden have extended syntactic closures
to obtain an alternative low-level macro facility.
The macro committee has not endorsed any particular
low-level facility, but does endorse the general concept of
a low-level facility that is compatible with the
high-level pattern language described in this appendix.

Several other people have contributed by working on macros
over the years.  Hal Abelson contributed by holding this
report hostage to the appendix on macros.

@c \extrapart{Bibliography and references}

@c  My reference for proper reference format is:
@c     Mary-Claire van Leunen.
@c     @emph{A Handbook for Scholars.}
@c     Knopf, 1978.
@c  I think the references list would look better in ``open'' format,
@c  i.e. with the three blocks for each entry appearing on separate
@c  lines.  I used the compressed format for SIGPLAN in the interest of
@c  space.  In open format, when a block runs over one line,
@c  continuation lines should be indented; this could probably be done
@c  using some flavor of latex list environment.  Maybe the right thing
@c  to do in the long run would be to convert to Bibtex, which probably
@c  does the right thing, since it was implemented by one of van
@c  Leunen's colleagues at DEC SRC.
@c   -- Jonathan

@c  I tried to follow Jonathan's format, insofar as I understood it.
@c  I tried to order entries lexicographically by authors (with singly
@c  authored papers first), then by date.
@c  In some cases I replaced a technical report or conference paper
@c  by a subsequent journal article, but I think there are several
@c  more such replacements that ought to be made.
@c   -- Will, 1991.

@c  This is just a personal remark on your question on the RRRS:
@c  The language CUCH (Curry-Church) was implemented by 1964 and
@c  is a practical version of the lambda-calculus (call-by-name).
@c  One reference you may find in Formal Language Description Languages
@c  for Computer Programming T. B. Steele, 1965 (or so).
@c   -- Matthias Felleisen

@node Bibliography and references, Index, Macros, Top
@ifset html
@unnumbered Bibliography
@end ifset
@ifclear html
@unnumbered Bibliography and references
@end ifclear
@c begin{thebibliography}{999}

@table @sc
@c new
@item [Abelson88]
@pindex Abelson88
Harold Abelson and Gerald Jay Sussman.
Lisp: a langauge for stratified design.
@cite{BYTE} 13(2):207--218, February 1988.

@item [SICP]
@pindex SICP
Harold Abelson and Gerald Jay Sussman with Julie Sussman.
@cite{Structure and Interpretation of Computer Programs.}
MIT Press, Cambridge, 1985.

@c new
@item [Adams88]
@pindex Adams88
Norman Adams and Jonathan Rees.
Object-oriented programming in Scheme.
In @cite{Proceedings of the 1988 Conference on Lisp
  and Functional Programming}, pages 277--288, August 1988.

@item [Bartley86]
@pindex Bartley86
David H. Bartley and John C. Jensen.
The implementation of PC Scheme.
In @cite{Proceedings of the 1986 ACM Conference on Lisp
  and Functional Programming}, pages 86--93.

@item [Scheme81]
@pindex Scheme81
John Batali, Edmund Goodhue, Chris Hanson, Howie Shrobe, Richard
  M. Stallman, and Gerald Jay Sussman.
The Scheme-81 architecture---system and chip.
In @cite{Proceedings, Conference on Advanced Research in VLSI},
  pages 69--77.
Paul Penfield, Jr., editor.
Artech House, 610 Washington Street, Dedham MA, 1982.

@c new
@item [bawden88]
@pindex Bawden88
Alan Bawden and Jonathan Rees.
Syntactic closures.
In @cite{Proceedings of the 1988 ACM Symposium on Lisp and
  Functional Programming}, pages 86--95.

@ifset html
Available as
<A HREF="ftp://altdorf.ai.mit.edu/pub/scheme-reports/synclo.dvi">
synclo.dvi
</A>,
<A HREF="ftp://altdorf.ai.mit.edu/pub/scheme-reports/synclo.ps">
synclo.ps
</A>,
<A HREF="ftp://altdorf.ai.mit.edu/pub/scheme-reports/synclo.tar">
synclo.tar
</A> or
<A HREF="ftp://altdorf.ai.mit.edu/pub/scheme-reports/synclo.tar.Z">
synclo.tar.Z
</A> (La@TeX{} files).
@end ifset
@ignore
todo
Church??
@end ignore

@item [Clinger84]
@pindex Clinger84
William Clinger.
The Scheme 311 compiler: an exercise in denotational semantics.
In @cite{Conference Record of the 1984 ACM Symposium on Lisp and
  Functional Programming}, pages 356--364.

@item [RRRS]
@pindex RRRS
William Clinger, editor.
The revised revised report on Scheme, or an uncommon Lisp.
MIT Artificial Intelligence Memo 848, August 1985.
Also published as Computer Science Department Technical Report 174,
  Indiana University, June 1985.

@c new
@item [Clinger88]
@pindex Clinger88
William Clinger.
Semantics of Scheme.
@cite{BYTE} 13(2):221--227, February 1988.

@c new
@item [howtoread]
@pindex howtoread
William Clinger.
How to read floating point numbers accurately.
In @cite{Proceedings of the ACM SIGPLAN '90 Conference
  on Programming Language Design and Implementation}, pages 92--101.
Proceedings published as @cite{SIGPLAN Notices} 25(6), June 1990.

@c new
@item [Clinger85]
@pindex Clinger85
William Clinger, Daniel P. Friedman, and Mitchell Wand.
A scheme for a higher-level semantic algebra.
In @cite{Algebraic Methods in Semantics}, pages 237--250.
J. Reynolds, M. Nivat, editor.
Cambridge University Press, 1985.

@c new
@item [Clinger88b]
@pindex Clinger88b
William Clinger, Anne Hartheimer, and Eric Ost.
Implementation strategies for continuations.
In @cite{Proceedings of the 1988 ACM Conference on Lisp and Functional
  Programming}, pages 124--131.

@c new
@item [macrosthatwork]
@pindex macrosthatwork
William Clinger and Jonathan Rees.
Macros that work.
In @cite{Proceedings of the 1991 ACM Conference on Principles of
  Programming Languages}, pages 155--162.

@c new
@item [Curtis90]
@pindex Curtis90
Pavel Curtis and James Rauen.
A module system for Scheme.
In @cite{Proceedings of the 1990 ACM Conference on Lisp and
  Functional Programming}, June 1990.
@ignore
todo
pages?
@end ignore

@c new
@item [Dybvig87]
@pindex Dybvig87
R. Kent Dybvig.
@cite{The Scheme Programming Language.}
Prentice-Hall, 1987.

@c  @item [Dybvig86]
@pindex Dybvig86
@c  R. Kent Dybvig, Daniel P. Friedman, and Christopher T. Haynes.
@c  Expansion-passing style: Beyond conventional macros.
@c  In @cite{Proceedings of the 1986 ACM Conference on Lisp and
@c    Functional Programming}, pages 143--150.

@c new; replaces the above
@item [Dybvig86]
@pindex Dybvig86
R. Kent Dybvig and Daniel P. Friedman and Christopher T. Haynes.
Expansion-passing style: a general macro mechanism.
@cite{Lisp and Symbolic Computation} 1(1):53--76, June 1988.

@c new
@item [Dybvig88]
@pindex Dybvig88
R. Kent Dybvig and Robert Hieb.
A variable-arity procedural interface.
In @cite{Proceedings of the 1988 ACM Symposium on Lisp and
  Functional Programming}, pages 106--115.

@c new
@item [Dybvig88]
@pindex Dybvig88
R. Kent Dybvig and Robert Hieb.
Engines from continuations.
@cite{Journal of Computer Languages} 14(2), pages 109--123,
1989.

@c new
@item [Dybvig88]
@pindex Dybvig88
R. Kent Dybvig and Robert Hieb.
Continuations and concurrency.
In @cite{Proceedings of the Second ACM SIGPLAN Notices
  Symposium on Principles and Practice of Parallel Programming},
pages 128--136, March 1990.

@c  technical report:

@item [Eisenberg85]
@pindex Eisenberg85
Michael A. Eisenberg.
Bochser: an integrated Scheme programming system.
MIT Laboratory for Computer Science Technical Report 349,
  October 1985.

@c new
@item [Eisenberg88]
@pindex Eisenberg88
Michael Eisenberg.
Harold Abelson, editor.
@cite{Programming In Scheme.}
Scientific Press, Redwood City, California, 1988.

@c new
@item [Eisenberg90]
@pindex Eisenberg90
Michael Eisenberg, with William Clinger and Anne Hartheimer.
Harold Abelson, editor.
@cite{Programming In MacScheme.}
Scientific Press, San Francisco, 1990.

@item [Feeley86]
@pindex Feeley86
Marc Feeley.
@iftex
Deux approches @`{a} l'implantation du language Scheme.
M.Sc. thesis, D@'{e}partement d'Informatique et de Recherche
  Op@'{e}rationelle, University of Montreal, May 1986.
@end iftex
@ifinfo
Deux approches `a l'implantation du language Scheme.
M.Sc. thesis, De'partement d'Informatique et de Recherche
  Ope'rationelle, University of Montreal, May 1986.
@end ifinfo

@c new
@item [Feeley87]
@pindex Feeley87
Marc Feeley and Guy LaPalme.
Using closures for code generation.
@cite{Journal of Computer Languages} 12(1):47--66, 1987.

@c new
@item [Feeley90]
@pindex Feeley90
Marc Feeley and James Miller.
A parallel virtual machine for efficient Scheme compilation.
In @cite{Proceedings of the 1990 ACM Conference on Lisp and
  Functional Programming}, June 1990.
@ignore
todo
pages?
@end ignore

@c new
@item [Felleisen87b]
@pindex Felleisen87b
Matthias Felleisen.
Reflections on Landin's J-Operator: a partly historical note.
@cite{Journal of Computer Languages} 12(3/4):197--207, 1987.

@c new
@item [Felleisen86b]
@pindex Felleisen86b
Matthias Felleisen and Daniel P. Friedman.
Control operators, the SECD-machine, and the lambda-calculus.
In @cite{3rd Working Conference on the Formal Description of
   Programming Concepts}, pages 193--219, August 1986.

@c new
@item [Felleisen86c]
@pindex Felleisen86c
Matthias Felleisen and Daniel P. Friedman.
A closer look at export and import statements.
@cite{Journal of Computer Languages} 11(1):29--37, 1986.

@c new
@item [Felleisen87]
@pindex Felleisen87
Matthias Felleisen and Daniel P. Friedman.
A calculus for assignments in higher-order languages.
In @cite{Conference Record of the 14th Annual ACM Symposium
  on Principles of Programming Languages}, pages 314--345, January 1987.

@c new
@item [Felleisen87d]
@pindex Felleisen87d
Matthias Felleisen and Daniel P. Friedman.
A reduction semantics for imperative higher-order languages.
In @cite{Lecture Notes in Computer Science},
@cite{Parallel Architectures and Languages Europe} 259:206--223, 1987.
De Bakker, Nijman and Treleaven, editors.
Springer-Verlag, Berlin.

@item [Felleisen86]
@pindex Felleisen86
Matthias Felleisen, Daniel P. Friedman, Eugene Kohlbecker, and Bruce Duba.
Reasoning with continuations.
In @cite{Proceedings of the Symposium on Logic in Computer Science},
  pages 131--141.
IEEE Computer Society Press, Washington DC, 1986.

@c  Does Felleisen87c replace Felleisen86 above?

@c new
@item [Felleisen87c]
@pindex Felleisen87c
Matthias Felleisen, Daniel P. Friedman, Eugene E. Kohlbecker, and Bruce Duba.
A syntactic theory of sequential control.
@cite{Theoretical Computer Science} 52:205--237, 1987.
@ignore
todo
5(2)?
@end ignore

@c new
@item [Felleisen88]
@pindex Felleisen88
Matthias Felleisen, Mitchell Wand, Daniel P. Friedman, and Bruce Duba.
Abstract continuations: a mathematical semantics for
  handling functional jumps.
In @cite{Proceedings of the 1988 ACM Symposium on Lisp and
  Functional Programming}, July 1988.
@ignore
todo
pages
@end ignore

@c  technical report
@item [Scheme311]
@pindex Scheme311
Carol Fessenden, William Clinger, Daniel P. Friedman, and Christopher Haynes.
Scheme 311 version 4 reference manual.
Indiana University Computer Science Technical Report 137, February 1983.
Superseded by @sc{[Scheme84]}.

@c new
@item [Franco90]
@pindex Franco90
John Franco and Daniel P. Friedman.
Towards a facility for lexically scoped, dynamic mutual recursion
  in Scheme.
@cite{Journal of Computer Languages} 15(1):55--64, 1990.

@item [Lisper]
@pindex Lisper
Daniel P. Friedman and Matthias Felleisen.
@cite{The Little LISPer.}
Science Research Associates, second edition 1986.

@item [littlelisper]
@pindex littlelisper
Daniel P. Friedman and Matthias Felleisen.
@cite{The Little LISPer.}
MIT Press, 1987.

@item [Friedman85]
@pindex Friedman85
Daniel P. Friedman and Christopher T. Haynes.
Constraining control.
In @cite{Proceedings of the Twelfth Annual Symposium on Principles of
  Programming Languages}, pages 245--254.
ACM, January 1985.

@item [Friedman84]
@pindex Friedman84
Daniel P. Friedman, Christopher T. Haynes, and Eugene Kohlbecker.
Programming with continuations.
In @cite{Program Transformation and Programming Environments,}
  pages 263--274.
P. Pepper, editor.
Springer-Verlag, 1984.

@item [Scheme84]
@pindex Scheme84
D. Friedman, C. Haynes, E. Kohlbecker, and M. Wand.
Scheme 84 interim reference manual.
Indiana University Computer Science Technical Report 153, January 1985.

@c new
@item [Friedman84b]
@pindex Friedman84b
Daniel P. Friedman and Mitchell Wand.
Reification: reflection without metaphysics.
In @cite{Conference Record of the 1984 ACM Symposium on Lisp
  and Functional Programming}, pages 348--355.

@item [Haynes86]
@pindex Haynes86
Christopher T. Haynes.
Logic continuations.
In @cite{Proceedings of the Third International Conference on
  Logic Programming,} pages 671--685.
Springer-Verlag, July 1986.
@c  and to appear in @i{The Journal of Logic Programming.}
@ignore
todo
find the journal reference
@end ignore

@item [Engines]
@pindex Engines
Christopher T. Haynes and Daniel P. Friedman.
Engines build process abstractions.
In @cite{Conference Record of the 1984 ACM Symposium on Lisp and
  Functional Programming,} pages 18--24.

@c  Does this replace Engines above?

@c new
@item [Haynes87b]
@pindex Haynes87b
Christopher T. Haynes and Daniel P. Friedman.
Abstracting timed preemption with engines.
@cite{Journal of Computer Languages} 12(2):109--121, 1987.

@c new
@item [Haynes87a]
@pindex Haynes87a
Christopher T. Haynes and Daniel P. Friedman.
Embedding continuations in procedural objects.
@cite{ACM Transactions on Programming Languages and Systems} 9(4):582--598,
  October 1987.

@c  @item [Haynes84]
@pindex Haynes84
@c  Christopher T. Haynes, Daniel P. Friedman, and Mitchell Wand.
@c  Continuations and coroutines.
@c  In @cite{Conference Record of the 1984 ACM Symposium on Lisp and
@c    Functional Programming,} pages 293--298.

@c  I assume the one below replaces the one above.

@c new
@item [Haynes86]
@pindex Haynes86
Christopher T. Haynes and Daniel P. Friedman and Mitchell Wand.
Obtaining coroutines with continuations.
@cite{Journal of Computer Languages} 11(3/4):143--153, 1986.

@item [Henderson82]
@pindex Henderson82
Peter Henderson.
Functional geometry.
In @cite{Conference Record of the 1982 ACM Symposium on Lisp and
  Functional Programming}, pages 179--187.

@c new
@item [Dybvig88]
@pindex Dybvig88
Robert Hieb, R. Kent Dybvig, and Carl Bruggeman.
Representing control in the presence of first-class continuations.
In @cite{Proceedings of the ACM SIGPLAN '90 Conference on Programming
  Language Design and Implementation},
pages 66--77, June 1990.
Proceedings published as @cite{SIGPLAN Notices} 25(6), June 1990.

@item [IEEE]
@pindex IEEE
@cite{IEEE Standard 754-1985.  IEEE Standard for Binary Floating-Point
Arithmetic.}  IEEE, New York, 1985.

@item [IEEEScheme]
@pindex IEEEScheme
@cite{IEEE Standard 1178-1990.  IEEE Standard for the Scheme
  Programming Language.}  IEEE, New York, 1991.

@item [Kohlbecker86]
@pindex Kohlbecker86
Eugene Edmund Kohlbecker Jr.
@cite{Syntactic Extensions in the Programming Language Lisp.}
PhD thesis, Indiana University, August 1986.

@item [hygienic]
@pindex hygienic
Eugene E. Kohlbecker, Daniel P. Friedman, Matthias Felleisen, and Bruce Duba.
Hygienic macro expansion.
In @cite{Proceedings of the 1986 ACM Conference on Lisp
  and Functional Programming}, pages 151--161.

@item [Kranz86]
@pindex Kranz86
David Kranz, Richard Kelsey, Jonathan Rees, Paul Hudak, James Philbin,
  and Norman Adams.
Orbit: An optimizing compiler for Scheme.
In @cite{Proceedings of the SIGPLAN '86 Symposium on Compiler
  Construction}, pages 219--233.
ACM, June 1986.
Proceedings published as @cite{SIGPLAN Notices} 21(7), July 1986.

@item [Kranz88]
@pindex Kranz88
David Kranz.
@cite{Orbit: An optimizing compiler for Scheme.}
PhD thesis, Yale University, 1988.

@item [Landin65]
@pindex Landin65
Peter Landin.
A correspondence between Algol 60 and Church's lambda notation: Part I.
@cite{Communications of the ACM} 8(2):89--101, February 1965.

@item [McDermott80]
@pindex McDermott80
Drew McDermott.
An efficient environment allocation scheme in an interpreter for a
  lexically-scoped lisp.
In @cite{Conference Record of the 1980 Lisp Conference,} pages
  154--162.
@c  The Lisp Conference, P.O. Box 487, Redwood Estates CA,
@c   1980.
Proceedings reprinted by ACM.

@item [MITScheme]
@pindex MITScheme
MIT Department of Electrical Engineering and Computer Science.
Scheme manual, seventh edition.
September 1984.

@item [Muchnick80]
@pindex Muchnick80
Steven S. Muchnick and Uwe F. Pleban.
A semantic comparison of Lisp and Scheme.
In @cite{Conference Record of the 1980 Lisp Conference}, pages 56--64.
@c  The Lisp Conference, 1980.
Proceedings reprinted by ACM.

@item [Naur63]
@pindex Naur63
Peter Naur et al.
Revised report on the algorithmic language Algol 60.
@cite{Communications of the ACM} 6(1):1--17, January 1963.

@item [Penfield81]
@pindex Penfield81
Paul Penfield, Jr.
Principal values and branch cuts in complex APL.
In @cite{APL '81 Conference Proceedings,} pages 248--256.
ACM SIGAPL, San Francisco, September 1981.
Proceedings published as @cite{APL Quote Quad} 12(1), ACM, September 1981.

@c  technical report

@item [Pitman85]
@pindex Pitman85
Kent M. Pitman.
Exceptional situations in Lisp.
MIT Artificial Intelligence Laboratory Working Paper 268, February 1985.

@c  technical report

@item [Pitman83]
@pindex Pitman83
Kent M. Pitman.
The revised MacLisp manual (Saturday evening edition).
MIT Laboratory for Computer Science Technical Report 295, May 1983.

@item [Pitman80]
@pindex Pitman80
Kent M. Pitman.
Special forms in Lisp.
In @cite{Conference Record of the 1980 Lisp Conference}, pages 179--187.
@c  The Lisp Conference, 1980.
Proceedings reprinted by ACM.

@c new
@item [Plebanthesis]
@pindex Plebanthesis
Uwe F. Pleban.
@cite{A Denotational Approach to Flow Analysis and Optimization of Scheme,
A Dialect of Lisp.} PhD thesis, University of Kansas, 1980.

@item [Rees89]
@pindex Rees89
Jonathan A. Rees.
@cite{Modular Macros}.
M.S. thesis, MIT, May 1989.

@item [Rees82]
@pindex Rees82
Jonathan A. Rees and Norman I. Adams IV.
T: A dialect of Lisp or, lambda: The ultimate software tool.
In @cite{Conference Record of the 1982 ACM Symposium on Lisp and
  Functional Programming}, pages 114--122.

@item [Rees84]
@pindex Rees84
Jonathan A. Rees, Norman I. Adams IV, and James R. Meehan.
The T manual, fourth edition.
Yale University Computer Science Department, January 1984.

@item [R3RS]
@pindex R3RS
Jonathan Rees and William Clinger, editors.
The revised(3) report on the algorithmic language Scheme.
In @cite{ACM SIGPLAN Notices} 21(12), pages 37--79, December 1986.

@ifset html
Available as
<A HREF="ftp://altdorf.ai.mit.edu/pub/scheme-reports/r3rs.tar">
r3rs.tar
</A> (La@TeX{} files).
@end ifset

@c new this
@item [R4RS]
@pindex R4RS
William Clinger and Jonathan Rees, Editors.
Revised(4) Report on the Algorithmic Language Scheme.
In @cite{ACM Lisp Pointers IV} (July-September 1991).

@ifset html
Available as
<A HREF="ftp://altdorf.ai.mit.edu/pub/scheme-reports/r4rs.dvi">
r4rs.dvi
</A>,
<A HREF="ftp://altdorf.ai.mit.edu/pub/scheme-reports/r4rs.dvi.Z">
r4rs.dvi.Z
</A>,
<A HREF="ftp://altdorf.ai.mit.edu/pub/scheme-reports/r4rs.ps">
r4rs.ps
</A>,
<A HREF="ftp://altdorf.ai.mit.edu/pub/scheme-reports/r4rs.ps.Z">
r4rs.ps.Z
</A>, or
<A HREF="ftp://altdorf.ai.mit.edu/pub/scheme-reports/r4rs.tar">
r4rs.tar
</A> or
<A HREF="ftp://altdorf.ai.mit.edu/pub/scheme-reports/r4rs.tar.Z">
r4rs.tar.Z
</A> (La@TeX{} files).
@end ifset

@item [Reynolds72]
@pindex Reynolds72
John Reynolds.
Definitional interpreters for higher order programming languages.
In @cite{ACM Conference Proceedings}, pages 717--740.
ACM,
@ignore
todo
month?
@end ignore
 1972.

@item [Rozas84]
@pindex Rozas84
Guillermo J. Rozas.
Liar, an Algol-like compiler for Scheme.
S. B. thesis, MIT Department of Electrical Engineering and Computer
  Science, January 1984.

@c new
@item [schflow]
@pindex schflow
Olin Shivers.
Control flow analysis in Scheme.
@cite{Proceedings of the SIGPLAN 1988 Conference on
  Programming Language Design and Implementation}, pages 164--174.
Proceedings published as @cite{SIGPLAN Notices} 23(7), July 1988.

@c new
@item [Sitaram90]
@pindex Sitaram90
Dorai Sitaram and Matthias Felleisen.
Control delimiters and their hierarchies.
@cite{Lisp and Symbolic Computation} 3(1):67--99, January 1990.

@c  technical report

@item [Smith84]
@pindex Smith84
Brian C. Smith.
Reflection and semantics in a procedural language.
MIT Laboratory for Computer Science Technical Report 272, January 1982.

@c new
@item [Springer89]
@pindex Springer89
George Springer and Daniel P. Friedman.
@cite{Scheme and the Art of Programming.}
MIT Press and McGraw-Hill, 1989.

@item [Srivastava85]
@pindex Srivastava85
Amitabh Srivastava, Don Oxley, and Aditya Srivastava.
An(other) integration of logic and functional programming.
In @cite{Proceedings of the Symposium on Logic Programming}, pages 254--260.
IEEE, 1985.

@c  technical report
@item [Stallman80]
@pindex Stallman80
Richard M. Stallman.
Phantom stacks---if you look too hard, they aren't there.
MIT Artificial Intelligence Memo 556, July 1980.

@c  NOTE -- there should not be a comma between ``Steele'' and ``Jr.''
@item [Declarative]
@pindex Declarative
Guy Lewis Steele Jr.
Lambda, the ultimate declarative.
MIT Artificial Intelligence Memo 379, November 1976.

@item [Debunking]
@pindex Debunking
Guy Lewis Steele Jr.
Debunking the ``expensive procedure call'' myth, or procedure call
  implementations considered harmful, or lambda, the ultimate GOTO.
In @cite{ACM Conference Proceedings}, pages 153--162.
ACM, 1977.

@item [Macaroni]
@pindex Macaroni
Guy Lewis Steele Jr.
Macaroni is better than spaghetti.
In @cite{Proceedings of the Symposium on Artificial Intelligence and
  Programming Languages}, pages 60--66.
These proceedings were published as a special joint issue of
  @cite{SIGPLAN Notices} 12(8) and @cite{SIGART Newsletter} 64, August
  1977.

@item [Rabbit]
@pindex Rabbit
Guy Lewis Steele Jr.
Rabbit: a compiler for Scheme.
MIT Artificial Intelligence Laboratory Technical Report 474, May 1978.

@c new
@item [renamegoto]
@pindex renamegoto
Guy Lewis Steele Jr.
Compiler optimization based on viewing LAMBDA as RENAME + GOTO.
In @cite{AI: An MIT Perspective.}
Patrick Henry Winston Richard Henry Brown, editor.
MIT Press, 1980.

@item [CLoverview]
@pindex CLoverview
Guy Lewis Steele Jr.
An overview of Common Lisp.
In @cite{Conference Record of the 1982 ACM Symposium on Lisp and
  Functional Programming}, pages 98--107.

@item [CLtL]
@pindex CLtL
Guy Lewis Steele Jr.
@cite{Common Lisp: The Language.}
Digital Press, Burlington MA, 1984.

@item [Imperative]
@pindex Imperative
Guy Lewis Steele Jr. and Gerald Jay Sussman.
Lambda, the ultimate imperative.
MIT Artificial Intelligence Memo 353, March 1976.

@item [Scheme78]
@pindex Scheme78
Guy Lewis Steele Jr. and Gerald Jay Sussman.
The revised report on Scheme, a dialect of Lisp.
MIT Artificial Intelligence Memo 452, January 1978.

@item [TAOTI]
@pindex TAOTI
Guy Lewis Steele Jr. and Gerald Jay Sussman.
The art of the interpreter, or the modularity complex (parts zero, one,
  and two).
MIT Artificial Intelligence Memo 453, May 1978.

@item [DOALBP]
@pindex DOALBP
Guy Lewis Steele Jr. and Gerald Jay Sussman.
Design of a Lisp-based processor.
@cite{Communications of the ACM} 23(11):628--645, November 1980.

@item [Dream]
@pindex Dream
Guy Lewis Steele Jr. and Gerald Jay Sussman.
The dream of a lifetime: a lazy variable extent mechanism.
In @cite{Conference Record of the 1980 Lisp Conference}, pages 163--172.
@c  The Lisp Conference, 1980.
Proceedings reprinted by ACM.

@item [howtoprint]
@pindex howtoprint
Guy Lewis Steele Jr. and Jon L White.
How to print floating point numbers accurately.
In @cite{Proceedings of the ACM SIGPLAN '90 Conference
  on Programming Language Design and Implementation}, pages 112--126.
Proceedings published as @cite{SIGPLAN Notices} 25(6), June 1990.

@item [Sussman82]
@pindex Sussman82
Gerald Jay Sussman.
Lisp, programming and implementation.
In @cite{Functional Programming and its Applications.}
Darlington, Henderson, Turner, editor.
Cambridge University Press, 1982.

@item [Scheme75]
@pindex Scheme75
Gerald Jay Sussman and Guy Lewis Steele Jr.
Scheme: an interpreter for extended lambda calculus.
MIT Artificial Intelligence Memo 349, December 1975.

@item [Scheme79]
@pindex Scheme79
Gerald Jay Sussman, Jack Holloway, Guy Lewis Steele Jr., and Alan Bell.
Scheme-79---Lisp on a chip.
@cite{IEEE Computer} 14(7):10--21, July 1981.

@item [Stoy77]
@pindex Stoy77
Joseph E. Stoy.
@cite{Denotational Semantics: The Scott-Strachey Approach to
  Programming Language Theory.}
MIT Press, Cambridge, 1977.

@item [TI85]
@pindex TI85
Texas Instruments, Inc.
@cite{TI Scheme Language Reference Manual.}
Preliminary version 1.0, November 1985.
@ignore
todo
get a more recent reference
@end ignore

@item [Vegdahl89]
@pindex Vegdahl89
Steven R. Vegdahl and Uwe F. Pleban.
The runtime environment for Screme, a Scheme implementation on the 88000.
In @cite{Proceedings of the Third International Conference on Architectural
  Support for Programming Languages and Operating Systems},
  pages 172--182, April 1989.

@item [Wand78]
@pindex Wand78
Mitchell Wand.
Continuation-based program transformation strategies.
@cite{Journal of the ACM} 27(1):174--180, 1978.

@item [Wand80]
@pindex Wand80
Mitchell Wand.
Continuation-based multiprocessing.
In @cite{Conference Record of the 1980 Lisp Conference}, pages 19--28.
Proceedings available from ACM.

@c new
@item [Wand86]
@pindex Wand86
Mitchell Wand.
@cite{Finding the source of type errors.}
In @cite{Conference Record of the Thirteenth Annual Symposium on
  Principles of Programming Languages}, pages 38--43, 1986.
@ignore
todo
make sure this is relevant
@end ignore

@c new
@item [tower]
@pindex tower
Mitchell Wand.
The mystery of the tower revealed: a non-reflective description of the reflective tower.
In @cite{Proceedings of the 1986 ACM Symposium on LISP and Functional
  Programming}, pages 298--307, August 1986.

@c new
@item [Wand78]
@pindex Wand78
Mitchell Wand and Daniel P. Friedman.
Compiling lambda expressions using continuations and factorizations.
@cite{Journal of Computer Languages} 3:241--263, 1978.

@c  This next one probably replaces tower above, but the above is
@c  probably more widely available.

@c new
@item [Wand88]
@pindex Wand88
Mitchell Wand and Daniel P. Friedman.
The mystery of the tower revealed: a non-reflective description of the
  reflective tower.
In @cite{Meta-Level Architectures and Reflection}, pages 111--134.
P. Maes and D. Nardi, editor.
Elsevier Sci. Publishers B.V. (North Holland), 1988.

@end table

@node Index,  , Bibliography and references, Top
@unnumbered Alphabetic index of definitions of concepts, keywords, and procedures

@c The principal entry for each term, procedure, or keyword is listed
@c first, separated from the other entries by a semicolon.

@unnumberedsec Concepts
@printindex cp

@unnumberedsec Keywords
@printindex vr
@page
@unnumberedsec Procedures
@printindex fn
@ifinfo
@unnumberedsec References
@printindex pg
@end ifinfo
@contents
@bye
